Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get query list that does not exist in another model in Django ORM?

I have three table:

Table1

class Table1(models.Model):
    field1 = model.CharField(...)
    field2 = model.CharField(...)

Table2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can work with .exclude(…) [Django-doc]:

Table1.objects.exclude(table3__table2_id=1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading