この作業のようなことをすることが可能です:
class Book(models.Model):
voters = models.ManyToManyField(User, blank=True)
vote = models.IntegerField() # summary of all votes
def average_vote(self):
return int(vote/self.annotate(Count('voters')))
たぶん、このようなものですか?
class Book(models.Model):
voters = models.ManyToManyField(User, blank=True)
vote = models.IntegerField() # summary of all votes
def average_vote(self):
return int(self.vote/self.voters.all().count())
それがうまくいくかどうか教えてください。私はそれをテストしていません。
デフォルトのマネージャーをオーバーライドして、常に注釈付きのクエリセットを返すようにします。
class BookUserManager(models.Manager):
def get_query_set(self, *args, **kwargs):
return super(BookUserManager, self).get_query_set(*args, **kwargs).annotate(average_vote=models.Avg('books__vote'))
class BookUser(User):
objects = BookUserManager()
class Meta:
proxy = True
class Book(models.Model):
# Next line has been changed to use proxy model. This *will* affect the m2m table name.
voters = models.ManyToManyField(BookUser, blank=True, related_name='books')
vote = models.IntegerField() # summary of all votes
objects = BookManager()
次に、ユーザー モデルの他の属性と同じように値を取得できます。
user = BookUser.objects.get(username='joe')
print user.average_vote
更新:申し訳ありません...すべて間違っています。それは私が質問をあまりにも早く読んだために得たものです。User
実際にはnotに注釈を付ける必要がありますBook
が、User
is から来ているためdjango.contrib.auth
(私は推測しています)、それは不可能であるか、少なくともより多くの手順が必要です。上記のコードが更新されました。