2010-02-26 48 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實例本身還沒有被保存,所以它不會有主鍵,因此我們不希望能夠找到任何與尚不存在的東西相關的東西(從數據庫的角度來看) 。