Select_related() backwards relation - auto model population
Posted
by
Nick
on Stack Overflow
See other posts from Stack Overflow
or by Nick
Published on 2011-01-06T23:23:45Z
Indexed on
2011/01/06
23:53 UTC
Read the original article
Hit count: 113
django
|django-models
Hi. If I have the following model:
class Contact(models.Model)
name = models.CharField(max_length=100)
...
class ContactAddress(models.Model)
line1 = models.CharField(max_length=100)
line2 = models.CharField(max_length=100)
...
contact = models.ForeignKey(Contact)
I now want to grab all Contacts and for the address to be auto populated. What would be the best way to do this? The only way I have found so far is to filter out the Contacts I want and loop around each contact and assign this to Contact.addresses. I then use this for outputting each Contacts address within a template.
Is there a better way of doing this? Select_related() almost does what I want, but doesn't seem to be able to work in the opposite direction.
Thanks in advance for your help on this one!
© Stack Overflow or respective owner