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)
...
CodePudding user response:
# 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)
CodePudding user response:
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/