I want to create a queryset that returns only the cars that had the last approved revision. It is known that there may be n cars, and each car has a history of revisions, so there may be no revisions for each car.
class Carro(models.Model):
marca = models.CharField(max_length=100)
class Revisao(models.Model):
carro = models.ForeignKey(Carro)
data = models.DateField()
aprovado = models.BooleanField(default=False)
I'm currently performing a non-performative algorithm with the following logic:
lista_de_aprovados = []
for carro in Carro.objects.filter(revisao=True):
try:
carro_aprovado = carro.revisao_set.filter(aprovado=True).latest('data')
except ObjectsDoesNotExist:
pass
else:
lista_de_aprovados.append(carro_aprovado)
carros_aprovados = Carros.objects.filter(id__in=[l.pk for l in lista_de_aprovados])
Would there be a way to accomplish this with just a queryset? I'm using Django 1.8 and the problem is that I'm performing this same logic more than once and this is slowing down a bit when loading the page. As I said earlier, the idea is a queryset that only returns the cars that had the last approved revision.
Carros.objects.filter(revisao=True).filter(...logica)