I have three table:
Table1
class Table1(models.Model):
field1 = model.CharField(...)
field2 = model.CharField(...)
Table2
class Table2(models.Model):
field1 = model.CharField(...)
field2 = model.CharField(...)
Table3
class Table3(models.Model):
table1 = model.ForeignKey(Table1)
table2 = model.ForeignKey(Table2)
I want to get all Table1 data that does not exists in Table3 with a which also includes Table2.
For Example: In Table1 I have three rows: rows1, rows2, rows3
In Table2 I have One rows: r1
In Table3 I have One rows: table1 = rows1 table2 = r1
I want to get rows2 and rows3 from Table1 when I am searching against Table2s r1 in Table3
I can get my expected result using this code:
table3 = Table3.objects.filter(table2=Table2.objects.get(id=1)).values_list('table1')
queryset = Table1.objects.filter(~Q(id__in=table3 ))
My Question now is there any better way to do this?
Thanks
CodePudding user response:
You can work with .exclude(…)
[Django-doc]:
Table1.objects.exclude(table3__table2_id=1)