Django: using objects.values() and get ForeignKey data in template

前端 未结 1 1547
故里飘歌
故里飘歌 2020-12-23 14:40

I have a Django app where my main Model has ForeignKey fields to other DB tables.

class Bugs(models.Model):
    bug_id = models.PositiveIntegerField(primary_         


        
相关标签:
1条回答
  • 2020-12-23 15:18

    I use this method all of the time. You are correct. It only returns the values, so you have to use the "__" notation to get the value from the ForeignKey. For example:

    # Get all of the bugs
    bugs = Bugs.objects.filter(
        active=True,
    ).order_by(
        'priority__sortkey',
        'bug_severity__sortkey',
    ).values(
        'bug_id',
        'priority', # Only the pk (id) of the bug priority FK
        'priority__value', # Equal to bug.priority.value
        'bug_severity',
        'bug_severity__some_value', # Equal to bug.priority.some_value
    )
    

    Now, in your template, you do:

    {% for bug in bugs %}
        <tr class="bugrow">
            <td>{{ bug.bug_id }}</td>
            <td>{{ bug.priority }}</td>
            <td>{{ bug.priority__value }}</td>
            <td>{{ bug.bug_severity }}</td>
            <td>{{ bug.bug_severity__some_value }}</td>
        </tr>
    {% endfor %}
    

    This is covered in the QuerySet.values() documentation, near the bottom:

    You can also refer to fields on related models with reverse relations through OneToOneField, ForeignKey and ManyToManyField attributes:

    Blog.objects.values('name', 'entry__headline')
    [{'name': 'My blog', 'entry__headline': 'An entry'},
     {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]
    
    0 讨论(0)
提交回复
热议问题