views:

218

answers:

1

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):
         ????
+10  A: 

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_set attribute:

some_foo.bar_set.all()

Or you can use the related_name argument to ForeignKey to specify the attribute which should hold the reverse relationship Manager:

class Foo(models.Model):
     name = models.CharField()

class Bar(models.Model):
     title = models.CharField()
     foo = models.ForeignKey(Foo, related_name='bars')

...

some_foo.bars.all()
insin