Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queries: how to filter objects to exclude id which is in a list?

Tags:

list

django

How can I filter in a query so the result excludes any object instances with ID belonging to a list?

Lets say I have:

object_id_list = [1, 5, 345]  MyObject.objects.filter(Q(time__gte=datetime.now()) & Q( ... what to put here? ... )) 

Something in the style of "SELECT * FROM ... WHERE id NOT IN (...)"

like image 909
ria Avatar asked Mar 01 '10 06:03

ria


2 Answers

MyObject.objects.filter(time__gte=datetime.now()).exclude(id__in=object_id_list) 
like image 61
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 03:10

Ignacio Vazquez-Abrams


You can also do this using the Q object:

from django.db.models import Q  MyObject.objects.filter(time__gte=datetime.now()).filter(~Q(id__in=object_id_list)) 
like image 41
javed Avatar answered Oct 01 '22 04:10

javed