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

261👍

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

33👍

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

0👍

try this:

from django.db import connection
def executeQuery(self, sql, params=[]):
  with connection.cursor() as cursor:
     cursor.execute(
        sql,
        params
      )

use:

list = [1, 2, 3]

"""only add map(str, list) if your comparing integers"""

if len(list) > 0: # only if the list is not empty 
   executeQuery(f"SELECT * FROM WHERE id NOT IN ({({','.join(map(str, list))})})")

Leave a comment