2011-10-13 44 views
0
class Author(Model): 
    state = models.CharField('ST') 

class Essay(Model): 
    authors = models.ManyToManyField("Author", 
     through='EssayAuthor') 

>> mylist 
[ <Essay: A1>, <Essay: B4>, <Essay: C9>, <Essay: A3> ... ] 

mylist是QuerySet。 我想添加另一個屬性爲(s)state mylist Essay的每個實例。假定具有多個作者的書籍的狀態是相同的。因此,對於有兩位作者的論文,使用哪個作者並不重要。如何使用新屬性註釋所有對象?

因此,我希望能夠做到這一點:

>> essay0 = mylist[0] 
>> essay0.state 
'AK' 

annotate方法僅適用於數字/浮點值有用;所以我不能使用它。如果我使用生成器來注入屬性,我如何重建QuerySet?

回答

1

你可以在模型類中做這個嗎?

class Essay(Model): 
    authors = models.ManyToManyField("Author", 
     through='EssayAuthor') 

    @property 
    def state(self): 
     if self.authors.count(): 
      return self.authors[0].state 
     else: 
      return null 

我不認爲你可以註釋你的查詢集在這種情況下,蒼蠅,尤其是隨着「只用一個作家如果有多個」邏輯。另一種選擇是使用extra()爲這些附加數據構建更復雜的SQL查詢。

相關問題