Matt Fellows
Matt Fellows

Reputation: 6532

Django model calculated field from one to many relationship

I have inherited some code with a django API and am trying to understand / get to grips with how to modify it appropriately..

I have a Model class called Asset and a Model class called Calibration.

A Calibration has a many to one relationship with Asset so:

class Calibration(Record):
    ...
    asset = models.ForeignKey(Asset, relatedName = "calibrationRecords")
    ...

And when I look at an individual Asset I can see the Calibration records as one would expect.

On another section of the API I can list all the Assets for a given Customer, however on this page, the calibrationRecords link is not shown.

This is kind of OK as I don't actually want to see all the Calibration records on this view, but I would like to see the last (most recent) Calibration record here, so in essence adding a calculated field onto this Model?

Where should this calculation go, and how is the best way to do it?

Upvotes: 0

Views: 464

Answers (1)

Andrea Vassallo
Andrea Vassallo

Reputation: 150

If you want to add a method to filter a model you can just add a model.Manager

E.g.

class ReviewerManager(models.Manager):
    def get_all_the_younger_reviewers(self):
        return self.get_queryset().filter(age__lt=18)

class Reviewer(models.Model):
    first_name = models.CharField(max_lenght=50, null=False, blank=False)
    last_name = models.CharField(max_lenght=50, null=False, blank=False)
    age = models.IntegerField()

    objects = ReviewerManager()

    @property
    def full_name(self):
        return self.first_name + " " + self.last_name

Now you can filter using new method:

Reviewer.objects.get_all_the_younger_reviewers()

Upvotes: 1

Related Questions