2010-02-26 51 views
1

我在Django以下问题..我在models.py保存有许多一对多在Django问题关系

class Proposal(models.Model): 
    #whatever.... 
    credit =models.FloatField(null=True, blank=True) 
    def save(): 
     #here credit is saved based on some calculation (succesfully) 

class Author(models.Model): 
    #whatever.... 
    balance = models.FloatField(null=True,blank=True) 
    proposal = models.ManyToManyField(Proposal,null=True,blank=True) 


    def save(self, force_insert=False, force_update=True): 

     to_add = sum(self.proposal.all().values_list('credit',flat=True)) # a sum of credits 
     self.balance = self.balance + to_add # or F(self.balance) + to_add, anyway 
     try: 
      super(Author, self).save(force_insert, force_update) 
     except IntegrityError: 
      super(Author, self).save(force_insert=True, force_update=False) 

所以我创建管理员,并从笔者的建议内的作家,我“保存”提案对象,确定,信用成功保存,然后我保存作者,但没有更新余额。发生这种情况,如果只有我重新保存作者对象..

有什么建议吗?

回答

1

让我说,我不知道你有什么问题,但我不认为这是一个好主意,尝试这样做,因为你试图。通常在计算一个数据集合中的一个数据以便在查找而不是保存并且有很好理由的情况下,通常更可取。即使上述方法按照您预期的方式工作,但您仍然有必须在Author本身未直接更改时保存Author对象。更好的做这样的事情:

class Author(models.Model): 
    proposal = models.ManyToManyField(Proposal,null=True,blank=True) 

    def get_balance(self): 
     return sum(self.proposal.all().values_list('credit',flat=True)) 

如果你真的需要写author.balance代替author.get_balance方便,考虑python properties。如果出现这种情况,读取操作比写入操作更频繁,而您希望针对性能进行优化,请考虑缓存并标记数据已更改。

0

我期望第一次调用Author.save时,self.proposal.all()将是一个空集。 (惊讶它实际上并没有错误)。由于Author实例本身还没有被保存,所以它不会有主键,因此我们不希望能够找到任何与尚不存在的东西相关的东西(从数据库的角度来看) 。