Skip to content
Advertisement

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

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(...)

    @property
    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

Advertisement

Answer

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

You can call it on an instance:

Addition.objects.all()[0].c()

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

from django.db.models import F

Addiction.objects.annotate(sum_a_b=F('a')+F('b'))

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement