我正在使用 Django ORM 从数据库中检索数据:
ws = Ws.objects.all()
ws = ws.filter(*q_objects, **filter_kwargs)
ws = ws.order_by(*sort_list)
ws = ws.annotate(created_unix=UnixTimestamp(F('created')), date_unix=UnixTimestamp(F('date')))))
total_sum = ws.aggregate(total=Sum('ts_time', output_field=DecimalField()))['total'])['total']
LIST_FIELDS[1], LIST_FIELDS[2] = 'created_unix', 'date_unix'
return JsonResponse({'table_data': list(ws.values_list(*LIST_FIELDS)), 'summ_time': total_sum}, safe=False) ```
我需要向 LIST_FIELDS 添加一个新列,对于具有多个字段匹配的每一对行,该列为 True 或 False
例如: 对于 LIST_FIELDS[0] 和 LIST_FIELDS[2]
列表_字段[0] | 列表_字段[1] | 列表_字段[2] | 列表_字段[3] |
---|---|---|---|
1 | 1 | 3 | 正确 |
1 | 1 | 2 | 正确 |
2 | 1 | 1 | 错误 |
1 | 1 | 2 | 正确 |
1 | 1 | 3 | 正确 |
我尝试询问GPT4,但T9固执地给我
ws = ws.annotate(
match=Case(
When(field1=F('field2'), then=Value(True)),
default=Value(False),
output_field=BooleanField()
)
)
但这就像在一行中比较
field1 == field2
我需要 True,如果 row1[field1] == row2[field1] and row1[field2] == row2[field2]
Exists
子查询: 检查具有相同值的行
from django.db.models import Exists, OuterRef, Q
UNIQUE_FIELDS = ['created_unix', 'date_unix']
ws = Ws.objects.filter(*q_objects, **filter_kwargs)
ws = Ws.annotate(
is_unique=Exists(
ws.filter(
~Q(pk=OuterRef('pk')), Q(**{k: OuterRef(k) for k in UNIQUE_FIELDS})
)
)
)
因此,我们从
Ws
(已过滤)中查找是否存在 ws
对象,该对象具有不同的主键 (~Q(pk=OuterRef('pk'))
),并且对于 UNIQUE_FIELDS
中的项目是相同的。