我有一个非常通用的文章模型,与标签模型有 m2m 关系。我想记录每个标签的使用情况,我认为最好的方法是对标签模型上的计数字段进行非规范化,并在每次保存文章时更新它。我怎样才能做到这一点,或者也许有更好的方法?
dmishe
问问题
3883 次
2 回答
3
这是 Django 1.2 中的一个新功能:http: //docs.djangoproject.com/en/dev/ref/signals/#m2m-changed
于 2010-04-28T20:10:44.940 回答
2
您可以通过为 M2M 关系创建中间模型并将其用作post_save
和post_delete
信号的挂钩来更新表中的非规范化列Article
。
例如,我对socloneQuestion
中的收藏计数执行此操作,其中s 与 s 具有 M2M 关系:User
Question
from django.contrib.auth.models import User
from django.db import connection, models, transaction
from django.db.models.signals import post_delete, post_save
class Question(models.Model):
# ...
favourite_count = models.PositiveIntegerField(default=0)
class FavouriteQuestion(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(User)
def update_question_favourite_count(instance, **kwargs):
"""
Updates the favourite count for the Question related to the given
FavouriteQuestion.
"""
if kwargs.get('raw', False):
return
cursor = connection.cursor()
cursor.execute(
'UPDATE soclone_question SET favourite_count = ('
'SELECT COUNT(*) from soclone_favouritequestion '
'WHERE soclone_favouritequestion.question_id = soclone_question.id'
') '
'WHERE id = %s', [instance.question_id])
transaction.commit_unless_managed()
post_save.connect(update_question_favourite_count, sender=FavouriteQuestion)
post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)
# Very, very naughty
User.add_to_class('favourite_questions',
models.ManyToManyField(Question, through=FavouriteQuestion,
related_name='favourited_by'))
在 django-developers 邮件列表上进行了一些讨论,讨论了实现一种以声明方式声明非规范化的方法,以避免编写像上面这样的代码:
于 2008-10-27T21:17:58.873 回答