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

时间:2010-03-01 06:55:53

标签: django list

如何在查询中过滤,以便结果排除任何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 (...)"

风格的东西

2 个答案:

答案 0 :(得分:136)

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

答案 1 :(得分:8)

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

from django.db.models import Q

MyObject.objects.filter(time__gte=datetime.now()).filter(~Q(id__in=object_id_list))