How to get related data on one to one field of a foreign key?

46 views
Skip to first unread message

Daniel Grace

unread,
Oct 25, 2014, 11:30:58 AM10/25/14
to django...@googlegroups.com
Hi,
I have a log table with a foreign key to the user table, and a userprofile table with a one to one field to the user table:

class Log(models.Model):
    user = models.ForeignKey(User)
    ...

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    picture = models.ImageField(upload_to='profile_images', blank=True)
    ... 

In my ListView I want to get the user profile for each log.  I know I can use select_related to get the related users of the log as follows:
queryset = Log.objects.select_related('user').order_by('created')

... but how do I get the related profiles and pass these on to the template, so I can for example display the picture for each log?

Thanks

Daniel Roseman

unread,
Oct 25, 2014, 11:50:56 AM10/25/14
to django...@googlegroups.com
That's what you've already done with your select_related call. What you should have asked is how you access that data in the template, and the answer is that you simply follow the relationship from your Log object:

{% for log in logs %}
{{ log.myfield }}
{{ log.userprofile.picture }}
{% endfor %}

--
DR.

Daniel Grace

unread,
Oct 25, 2014, 1:32:41 PM10/25/14
to django...@googlegroups.com
I just used the following:
{{ log.user.userprofile.picture }}
... and I didn't need the select_related.
Reply all
Reply to author
Forward
0 new messages