Executing Anti Join in Django ORM

為{幸葍}努か 提交于 2019-12-25 07:09:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!