How can I get a value from other model, based in other value from that same other model?

Tags: , ,

How can I get the proper “sumvalue” in the example? (which I only know how to represent in SQL):

class Addition(models.Model):
    location = models.ForeignKey(Place, ...)
    a = models.DecimalField(...)
    b = models.DecimalField(...)

    def c(self):
        return self.a + self.b

class Result(models.Model):
    place = models.ForeignKey(Place, ...)
    # I only know how to represent in SQL
    sumvalue = SELECT c FROM Addition WHERE location = place


In your case, c is not a field, but a property.

You can call it on an instance:


Now for what you’re trying to do, I really recommand you use annotate.

from django.db.models import F


You then have an additional field in your query called sum_a_b.

Source: stackoverflow