How to perform a Queryset returning the biggest date with Django

Asked

Viewed 75 times

1

I’m trying to perform a Queryset using Django, I want to return the most recent dates present in the database, along with the other fields, where I used the prefetch_related(). However, the use of Max('data') returns all data present.

These are the tables I’m working on on models.py...

#models.py
    class TipoServicos(models.Model):
            servico = models.ForeignKey(Servicos, on_delete=models.CASCADE)
            nomeServ = models.CharField(max_length=50)
        
            def __str__(self):
                return self.nomeServ
            
        class Controle(models.Model):
            cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE)
            data = models.DateTimeField(null=True, blank=True)
        
            def __str__(self):
                return '%s' % self.data
        
            class Meta:
                get_latest_by = "data"
        
        class StatusServico(models.Model):
            controle = models.ForeignKey(Controle, on_delete=models.CASCADE)
            tipo_servico = models.ForeignKey(TipoServicos, on_delete=models.CASCADE)
            status = models.CharField(max_length=10)
        
            def __str__(self):
                return '%s' % self.status

And my view where I do the Querys...

#views.py
def integra(request, servico):
    clientes = Clientes.objects.all().order_by('nome')
    servico = Servicos.objects.filter(nomeServ__iexact=servico)
    controle = Controle.objects.prefetch_related('statusservico_set').annotate(Max('data'))
    context= {
        'clientes': clientes,
        'controles': controle,
    }
    return render(request, 'app/integra.html', context)

For better visualization, this is the search I performed by SQL, where returns the last dates with the client ID.

select max(data), app_controle.cliente_id from app_controle
inner join app_statusservico on
    app_statusservico.controle_id = app_controle.id
inner join app_tiposervicos on 
     app_tiposervicos.id = app_statusservico.tipo_servico_id
where
    app_tiposervicos.servico_id = 1
group by app_controle.cliente_id
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.