Latest objects of every group with Django filter in mysql backend

Issue

I have 2 Models:

class WLSDomainName(BaseMixin):
    domain_name = models.CharField('Domain Name',max_length=255, null=False, blank=False)
    site_name = models.CharField('Site Name', max_length=10, choices = SITE_NAME, default='dc',blank=False, null=False)
    delete_status = models.BooleanField(default=False)

class DomainOverallHealthStatus(BaseMixin):
    domain_name = models.ForeignKey(WLSDomainName, on_delete=models.CASCADE, null=True, blank=False, related_name="overall_health_status_domain_name") 
    configuredServerCount = models.IntegerField(blank=True, null=True)
    activeServerCount = models.IntegerField(blank=True, null=True)
    overallServiceHealth = models.CharField(max_length=255, null=True, blank=True)
    activeThreadCount = models.IntegerField(blank=True, null=True)
    activeHttpSessionCount = models.IntegerField(blank=True, null=True)
    classification_time = models.CharField(max_length=20, null=True, blank=True)

I need to find the latest object from DomainOverallHealthStatus model for every object of WLSDomainName.

I have tried:

o_health = DomainOverallHealthStatus.objects.all().values('domain_name').annotate(Max('created')).order_by()

This query returning me only id and created.

<QuerySet [{'domain_name': 1, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 49, 217073, tzinfo=datetime.timezone.utc)}, {'domain_name': 2, 'created__max': datetime.datetime(2022, 8, 31, 9, 14, 50, 338368, tzinfo=datetime.timezone.utc)}]>

But I need to fetch every column of DomainOverallHealthStatus.

Solution

the query you wanted:

from django.db.models import Max, F

o_health = DomainOverallHealthStatus.objects.alias(
    latest=Max('domain_name__overall_health_status_domain_name__created')
).filter(
    created=F('latest')
)

Answered By – Amrez

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published