简体   繁体   中英

Model field on django should is the sum of other model

I'm new on Django and I have a problem.

I need to have two models, but with the particularity of that one of them have the field "total" that is the subtraction of two field of other model, but "total" has not be save on db.

class Account(models.Model):
    number = models.CharField()
    total = 0.0

    def __get_total(self):
        return movement.input - movement.output  
        # I don't know how to
        # join A with B
        # should be query about whole
        # movement of a particular account

    total = property(__get_total)


class Movement(models.Model):
    input = models.DecimalField()
    output = models.DecimalField()
    account = models.ForeignKey(Account, related_name='account')
def __total(self):
  from django.db.models import Sum
  obj=Movement.objects.filter(account=self).values('account').annotate(inSum=Sum('input'),outSum=Sum('output').first()
  total=obj['inSum']-obj['outSum']

You could move the import statement at the top of your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM