DisneylandSC
DisneylandSC

Reputation: 966

select_related on many to many with custom through table

I have two models, Foo and Bar, and I have created a many to many relationship with a custom through table, FooBar.

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

class Bar(models.Model):
    barfield = models.CharField()
    foos = models.ManyToManyField('Foo', through='FooBar', related_name='foo_bar')

class FooBar(models.Model):
    foo = models.ForeignKey(Foo, related_name='foobar')
    bar = models.ForeignKey(Bar, related_name='foobar')
    foobarfield= models.CharField()

What I would like to do is display all Bar records for a given instance of Foo, and for each such record also display the corresponding value of foobarfield. So I would get something like

  1. barfield_value1, foobarfield_value1
  2. barfield_value2, foobarfield_value2
  3. barfield_value3, foobarfield_value3
  4. ...

I can't seem to construct the correct query to do this though. I tried something like

Bar.objects.select_related('foobar').filter(foobar__foo = foo_instance)

Since I would expect foobar to be unique for a give instance of Foo but this does not seem to work. How do I get the result I want?

Upvotes: 0

Views: 385

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48982

Since you will have one result for every related row in the FooBar table, and since you want to access fields on that table (foobarfield), the most straightforward approach is to filter on FooBar:

foobars = FooBar.objects.select_related("bar").filter(foo=foo_instance)
for foobar in foobars:
    print(foobar.bar.barfield, foobar.foobarfield)

Upvotes: 1

Related Questions