Inner join from two not directly related models in Django
Let's say I have model like this (all irrelevant fields removed for clarity):
A(Model):
someFields = ... #irrelevant in this case
B(Model):
a = Fo开发者_如何学CreignKey(A)
my_data = ... #the data I need to retrieve
C(Model):
user = ForeingKey(User)
a = ForeignKey(A)
class Meta:
unique_together = ('user', 'a')
Now, how using Django queries can I get something equivalent to this SQL:
SELECT my_data FROM B WHERE B.a_id = C.a_id AND C.user = %user%
Lucky for you your query uses an existing relation.
B.objects.filter(a__c__user=someuser).distinct().values('my_data')
精彩评论