如何在查询中进行过滤,以使结果排除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 (...)"风格的东西
"SELECT * FROM ... WHERE id NOT IN (...)"
niknxzdl1#
MyObject.objects.filter(time__gte=datetime.now()).exclude(id__in=object_id_list)
wecizke32#
也可以使用Q对象执行此操作:
Q
from django.db.models import Q MyObject.objects.filter(time__gte=datetime.now()).filter(~Q(id__in=object_id_list))
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))})})")
3条答案
按热度按时间niknxzdl1#
wecizke32#
也可以使用
Q
对象执行此操作:rqqzpn5f3#
试试这个:
用途:
“"“仅在比较整数时添加map(str,list)”"”