I have two models. We’ll call them object A and object B. Their design looks something like this:
class Foo(models.Model): name = models.CharField() class Bar(models.Model): title = models.CharField() Foo= models.ForeignKey('myapp.Foo')
Now, suppose I want to make a method within Foo that returns all Bar objects that reference that instance of Foo. How do I do this?
class Foo(models.Model): name = models.CharField() def returnBars(self): ????
You get this for free:
http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects
By default, you can access a Manager which gives you access to related items through a
RELATEDCLASSNAME_setattribute:Or you can use the
related_nameargument toForeignKeyto specify the attribute which should hold the reverse relationship Manager: