Search code examples
pythondjangodjango-filter

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


How to filter all objects of the ViewModel if only the last InfoModel.check_by_client_a is True ?

I have the structure like this:

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)
    ...


Solution

  • Using a subquery expression you can annotate on ViewModel the value of the last InfoModel.check_by_client
    after that you can filter by this "new field" if it's true

    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)
    

    see more on: https://docs.djangoproject.com/en/4.0/ref/models/expressions/