Django 过滤器,如果查询中的最后一个值为真

Django filter, if only last value in a query is true

如果只有最后一个 InfoModel.check_by_client_aTrue,如何过滤 ViewModel 的所有对象?

我有这样的结构:

class InfoModel(model.Models):
    ...
    service = ForeingKey(ServiceModel)
    check_by_client_a = BooleanField()
    check_by_client_b = BooleanField()
    check_date = DateTimeFiled()
    ...

class ServiceModel(model.Models):
    ...

class ViewModel(model.Models):
    ...
    service = ForeingKey(ServiceModel)
    ...

# get last InfoModel
last_info_model = InfoModel.objects.filter(check_by_client_a=True).last()
if last_info_model:
    # filter all ViewModel for the service
    ViewModel.objects.filter(service_id=last_info_model.service_id)

使用子查询表达式,您可以在 ViewModel 上注释最后一个 InfoModel.check_by_client
的值 之后你可以通过这个“新字段”过滤,如果它是真的

ViewModel.objects.annotate(last_info_checked=Subquery(
            InfoModel.objects.filter(service=OuterRef('service'))
                             .order_by('-check_date')
                             .values('check_by_client_a')[:1])
                 .filter(last_info_checked=True)

查看更多信息:https://docs.djangoproject.com/en/4.0/ref/models/expressions/