NickP
NickP

Reputation: 1414

Getting exclusive (only one) latest related object from relationship

I have two models described as the following:

class Report(models.Model):
    report_name = models.CharField(max_length=140)
    report_description = models.TextField(null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)
    metric = models.ManyToManyField(Metric, through='MetricAssociation')

class Status(models.Model):
    report = models.ForeignKey(Report, on_delete=models.CASCADE)
    status = models.CharField(max_length=140)
    provided_by = models.ForeignKey(TeamMember, on_delete=models.CASCADE)
    date = models.DateTimeField() 

I have created an index page with all reports and attributes. I would like to pass through just the latest status for each report with the list of reports to be used in a view like this:

<td>{{ report.report_name }}</td>
<td>{{ report.last_updated }}</td>
<td>{{ report.latest_status }}</td>

Since the Report does not have a latest_status attribute but ideally the latest status is the latest by that report, how could I pass this through?

Upvotes: 0

Views: 36

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Quite simply: the "latest status" for a Report instance is

`your_report_instance.status_set.order_by("date").last()`

Now since this is a bit verbose, exposes too much of the implementation and is not accessible from a template, you just have to encapsulate the call in a getter method or property, ie:

class Report(models.Model):
    report_name = models.CharField(max_length=140)
    report_description = models.TextField(null=True, blank=True)
    last_updated = models.DateTimeField(null=True, blank=True)
    metric = models.ManyToManyField(Metric, through='MetricAssociation')

    @property
    def latest_status(self):
        return self.status_set.order_by("date").last()

Upvotes: 3

Related Questions