Django查询:如何过滤对象以排除列表中的ID?


87

如何过滤查询,以便结果排除ID属于列表的任何对象实例?

可以说我有:

object_id_list = [1, 5, 345]

MyObject.objects.filter(Q(time__gte=datetime.now()) & Q( ... what to put here? ... ))

风格的东西 "SELECT * FROM ... WHERE id NOT IN (...)"

Answers:


171
MyObject.objects.filter(time__gte=datetime.now()).exclude(id__in=object_id_list)

1
的名字是MyObject.objects什么?我在哪里可以读到这堂课?
Serge

@Serge MyObject可能与您的Django模型类有关。因此,例如,如果您具有UserProfile模型设置,则可能具有UserProfile.objects。
codeguy19年

谢谢,但即时消息询问正确.objects。它是什么?
Serge

14

您也可以使用Q对象执行此操作:

from django.db.models import Q

MyObject.objects.filter(time__gte=datetime.now()).filter(~Q(id__in=object_id_list))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.