Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform two inner joins in a queryset in Django

Tags:

python

sql

django

I have three models.

class A(models.Model):
    status = models.PositiveSmallIntegerField()
    status_time = models.DateTimeField(auto_now_add=True)
    b = models.ForeignKey(B)
    d=models.ForeignKey(D)

class B(models.Model):
    ***other Fileds*****
    c = models.OneToOneField(C)
    ***other fields***

class C(models.Model):
    c_name = models.CharField(max_length=9,unique=True)

I want to perform a query where i can get all the c_name.

SELECT * FROM A inner join B  on A.b_id=B.id inner join 
C  on B.c_id=C.id where A.d_id=1 and A.status=6

can anyone please help how to do. i found a similar question here, but it is too much complex to understand for a newbie like me. Thnak you so much already for any help.

like image 690
Aman Gupta Avatar asked Oct 30 '22 16:10

Aman Gupta


1 Answers

Something like this

C.objects.filter(b__a__status=6, b__a__d=1).values_list('c_name', flat=True).distinct()

or this

A.objects.filter(status=6, d=1).values_list('b__c__c_name', flat=True).distinct()
like image 140
vsd Avatar answered Nov 02 '22 22:11

vsd