0

I'm trying to do a QuerySet using Django, want to return the latest datetime from database, with the other fields, I used prefetch_related(). The Max('data') used return all the records in the database, not just the recent ones.

These are my models:

#models.py
    class TServices(models.Model):
            services = models.ForeignKey(Services, on_delete=models.CASCADE)
            servName = models.CharField(max_length=50)
        
            def __str__(self):
                return self.nomeServ
            
        class Control(models.Model):
            customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
            date = models.DateTimeField(null=True, blank=True)
        
            def __str__(self):
                return '%s' % self.date
        
            class Meta:
                get_latest_by = "date"
        
        class ServiceStatus(models.Model):
            control = models.ForeignKey(Control, on_delete=models.CASCADE)
            services_type = models.ForeignKey(TServices, on_delete=models.CASCADE)
            status = models.CharField(max_length=10)
        
            def __str__(self):
                return '%s' % self.status

My views, where I do the query in Django:

#views.py
def integr(request, servico):
    customer = Customer.objects.all().order_by('name')
    services = Services.objects.filter(servName__iexact=services)
    control = Control.objects.prefetch_related('servicestatus_set').annotate(Max('date'))
    context= {
        'customers': customer,
        'controls': control,
    }
    return render(request, 'app/integr.html', context)

This is the query that I made in my database and returned the recent date with the customer_id.

select max(date), app_control.customer_id from app_control
inner join app_servicestatus on
    app_servicestatus.control_id = app_control.id
inner join app_tservices on 
     app_tservices.id = app_servicestatus.services_type_id
where
    app_tservices.services_id = 1
group by app_control.customer_id
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marcos R.
  • 11
  • 4

0 Answers0