簡體   English   中英

django上的模型字段應為其他模型的總和

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

我是Django的新手,但是有問題。

我需要兩個模型,但是由於其中之一的特殊性,字段“ 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']

您可以將import語句移動到文件頂部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM