为了获得更好的性能,我想对数据进行非规范化处理,并在post模型中放入我的博客文章获得的投票总数:
class Post(models.Model):
""" Blog entry """
author = models.ForeignKey(User)
title = models.CharField(max_length=255)
text = models.TextField()
rating = models.IntegerField(default=0) # here is the sum of votes!
class Vote(models.Model):
""" Vote for blog entry """
post = models.ForeignKey(Post)
voter = models.ForeignKey(User)
value = models.IntegerField()
当然,我需要保持Post.rating
值的实际值。通常我会使用数据库触发器,但现在我决定发出一个post_save
信号(以减少数据库处理时间):
# vote was saved
@receiver(post_save, sender=Vote)
def update_post_votes(sender, instance, created, **kwargs):
""" Update post rating """
if created:
instance.post.rating += instance.value
instance.post.save()
else:
# if vote was updated, we need to remove the old vote value and add the new one
# but how...?
如何在保存实例值之前访问它?在数据库触发器中,我会有OLD
和NEW
的预定义,但是在post-save信号中有类似的东西吗?
更新
基于马克答案的解决方案:
# vote was saved
@receiver(pre_save, sender=Vote)
def update_post_votes_on_save(sender, instance, **kwargs):
""" Update post rating """
# if vote is being updated, then we must remove previous value first
if instance.id:
old_vote = Vote.objects.get(pk=instance.id)
instance.post.rating -= old_vote.value
# now adding the new vote
instance.post.rating += instance.value
instance.post.save()
我相信
post_save
太晚了,无法检索未修改的版本。顾名思义,此时数据已经写入数据库。您应该改用pre_save
。在这种情况下,您可以通过pk:old = Vote.objects.get(pk=instance.pk)
从数据库中检索模型,并检查当前实例和前一实例中的差异。这不是一个最优解,但它是有效的。
相关问题 更多 >
编程相关推荐