问题
I have two models:
class Note(model):
<attribs>
class Permalink(model):
note = foreign key to Note
I want to execute a query: get all notes which don't have a permalink. In SQL, I would do it as something like:
SELECT * FROM Note WHERE id NOT IN (SELECT note FROM Permalink);
Wondering how to do this in ORM.
Edit: I don't want to get all the permalinks out into my application. Would instead prefer it to run as a query inside the DB.
回答1:
you can use:
Note.objects.exclude(id__in=Permalink.objects.all().values_list('id', flat=True))
回答2:
You should be able to use this query:
Note.objects.filter(permalink_set__isnull=True)
来源:https://stackoverflow.com/questions/26597837/executing-anti-join-in-django-orm