Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select_related() backwards relation - auto model population

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!

like image 452
Nick Avatar asked Jan 06 '11 23:01

Nick


1 Answers

You are right, select_related only works forwards! To make more efficient reverse lookups see this!

like image 110
Bernhard Vallant Avatar answered Nov 12 '22 12:11

Bernhard Vallant