在django问题中保存多对多的关系 [英] save with many-to-many relationship in django problem

查看:448
本文介绍了在django问题中保存多对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django中有以下问题..我在models.py

I have the following problem in django.. I have in models.py

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)

所以我创建一个作者从管理员和作者的提案,我保存提案对象,好的,信用成功保存,然后我保存作者,但没有平衡更新。如果只重新保存作者对象,则会发生这种情况。

So I create an author from admin and from within the author a proposal, i "save" the proposal object, ok, credit succesfully saved, then i save the author, but no balance updated. This happens if only I re-save the author object..

任何建议?

推荐答案

让我说,我不知道你出了什么问题,但我不认为尝试这样做是个好主意。通常情况下,您可以从数据集合中计算一个数据,以便在查找上执行此操作,而不是在保存上,并且有很好的理由。即使上述方法按照预期的方式工作,您仍然有必要在作者对象时保存 code>本身没有直接改变。更好地做如下事情:

Let me say that I'm not sure what's going wrong for you, but I don't think it's a good idea to try to do this as you're attempting. It is usually preferable in situations where you calculate one datum from a collection of data to do that on lookup, not on save, and for good reason. Even if the above method worked as you expected it to, you'd still have the problem of having to save an Author object when the Author itself hasn't directly changed. Much better to do something like:

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属性。如果这是读写比写入更频繁且您希望优化性能的情况,请考虑缓存并标记数据已更改。

If you really need the convenience of writing author.balance instead of author.get_balance, consider python properties. If this is a situation where reads are more frequent than writes and you want to optimize for performance, consider caching and marking that the data has changed.

这篇关于在django问题中保存多对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆