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.
CodePudding user response:
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')
)