Django using wrong foreign key for joins
I have two relationships between models in Django, a many-to-many between Foo
and Bar
and a foreign key on Foo
pointed towards Bar
.
When I do a qu开发者_如何学Pythonery that involves both Foo
and Bar
, django insists on using the Foreign Key instead of the M2M to do the join.
(The M2M is the real data here, the Foreign Key is just a bit of caching so I can get the most recent Bar
created by a certain method.)
So for example (where foos
is the many-to-many relationship name on Bar
)
Bar.objects.filter(foos__attribute = True)
Doesn't return all of the Bar
s with that attribute, but only the one Bar
that Foo
is pointed at with the FK. How can I force it to use the M2M? Or is this a bad idea completely?
I figured it out, and it was definitely an instance of 'should have used real code for the example'.
I had the many-to-many relation on the Bar
table called 'foos' (lets say). The foreign key was automatically creating a related_name
on the Bar
table called 'foo'. I was not actually calling:
Bar.objects.filter(foos__attribute = True)
Like I said I was. I was calling:
Bar.objects.filter(foo__attribute = True)
Which was using the automatically-created related name of the Foreign Key 'foo' instead of the name of the many-to-many table 'foos'.
So lessons learned:
- Don't let django ever decide the related name for you
- Be careful with pluralization!
- Post real examples on SA
精彩评论