0

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.

1 Answer 1

1

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')
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. My problem is solved. But I am so sorry that I can't understand the query. Can you make me understand?
@Samrat for every health status, checks the related domain name and gets highest created field of its health statuses. Then checks created value of health status with the founded created value of previous step, and keeps it if they're equal.
if you didn't understand what i said, you can test the query and print its sql query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.