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

DjangoList

Django Problem Overview


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 (...)"

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionriaView Question on Stackoverflow
Solution 1 - DjangoIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - DjangoJavedView Answer on Stackoverflow