Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select values which not in another table with Django

How this SQL query can be translated to Django ORM statement?

SELECT field1, field2, field3
FROM table1
WHERE field1 NOT IN 
(SELECT 2_field1 FROM table2);

Kindly help! :)

ps
table1 and table2 not bounded with ForeignKey or ManyToMany

like image 366
Gill Bates Avatar asked Dec 31 '12 20:12

Gill Bates


1 Answers

Using two QuerySets, as shown in the docs.

inner_qs = table2.objects.all()
results = table1.objects.exclude(field1__in=inner_qs)
like image 111
voithos Avatar answered Sep 20 '22 01:09

voithos