简体   繁体   English

django上的模型字段应为其他模型的总和

[英]Model field on django should is the sum of other model

I'm new on Django and I have a problem. 我是Django的新手,但是有问题。

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. 我需要两个模型,但是由于其中之一的特殊性,字段“ total”是其他模型两个字段的减法,但是“ total”尚未保存在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. 您可以将import语句移动到文件顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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