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

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'}, ...]

Leave a Comment

tech