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

n3h0vuf2  于 2023-01-06  发布在  Go
关注(0)|答案(3)|浏览(138)

如何在查询中进行过滤,以使结果排除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 (...)"风格的东西

niknxzdl

niknxzdl1#

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

wecizke32#

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

from django.db.models import Q

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

rqqzpn5f3#

试试这个:

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

用途:

list = [1, 2, 3]

“"“仅在比较整数时添加map(str,list)”"”

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

相关问题