假设我们有一个表:
+--------------- ...
| id | old_id |
+--------------- ...
| ...
除了在old_id列中找到id之外,我如何根据一些自定义条件选择所有值?
我试过:
records = MyRecords.objects
.filter(<my custom criteria>)
.exclude(id__in=models.OuterRef('old_id'))
.order_by('-modified_at')
以及其他变体,但都无济于事。
基本上,我正在努力实现这种行为:
select * from mytable where
<custom criteria> and
not id in (select old_id from mytable where 1)
我认为你可以做到这一点:
ids_to_exclude = MyRecords.objects.all().values_list('old_id',flat=True)
#get unique values
ids_to_exclude = list(set(ids_to_exclude))
records = MyRecords.objects
.filter(<my custom criteria>)
.exclude(id__in= ids_to_exclude)
.order_by('-modified_at')
如果需要检查所有行,可能是其他行中的old_id
。
from django.db import models
# Please, never convert `old_ids` queryset below to list, tuple, set, etc.
# Keep it as queryset, for better performance.
old_ids = MyRecords.objects.values_list("old_id", flat=True)
MyRecords.objects.filter().exlcude(id__in=old_ids)
如果只检查同一行的old_id
:
MyRecords.objects.filter(
).annotate(
is_match_old_id=models.Case(
models.When(id=models.F("old_id"), then=True),
default=False,
output_field=models.BooleanField()
)
).filter(
is_match_old_id=False
)