如何在 Django ORM 中使用 Q & Q 修复排除

How to fix the exclude with Q & Q in Django ORM

我有一个带有过滤和排除的简单查询。排除 Q & Q 无效。

下面是我正在使用的查询。

start_date = (datetime(time.localtime().tm_year, time.localtime().tm_mon, 1) - timedelta(1)).replace(day=1)

data = models.Test.objects.filter(
            is_deleted=False).exclude(Q(status__in=[1,2,3]) & Q(modified_at__lt=start_date))\
            .select_related('created_by')\
            .prefetch_related('name')

我想让排除工作。如果我使用 exclude 两次,我就会得到结果。

From the doc

exclude(**kwargs)
Returns a new QuerySet containing objects that do not match the given lookup parameters. The lookup parameters (**kwargs) should be in the format described in Field lookups below. Multiple parameters are joined via AND in the underlying SQL statement, and the whole thing is enclosed in a NOT().

因此,只需使用 Q() 对象并用 逗号分隔 ,

.exclude(<b>Q(status__in=[1,2,3],Q(modified_at__lt=start_date)</b>)