'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 1:[1]
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/
Solution 2:[2]
# 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luid Duarte |
| Solution 2 | erajuan |
