我想做一个数据非规范化以获得更好的性能,并在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
值实际。 Nornally我会使用数据库触发器,但现在我决定发出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()
答案 0 :(得分:46)
我认为post_save
为时已晚,无法检索未经修改的版本。顾名思义,此时数据已经写入数据库。您应该使用pre_save
代替。在这种情况下,您可以通过pk:old = Vote.objects.get(pk=instance.pk)
从db检索模型,并检查当前实例和上一个实例的差异。
答案 1 :(得分:4)
这不是不是最佳解决方案,但可以。
@receiver(pre_save, sender=SomeModel)
def model_pre_save(sender, instance, **kwargs):
try:
instance._pre_save_instance = SomeModel.objects.get(pk=instance.pk)
except SomeModel.DoesNotExist:
instance._pre_save_instance = instance
@receiver(signal=post_save, sender=SomeModel)
def model_post_save(sender, instance, created, **kwargs):
pre_save_instance = instance._pre_save_instance
post_save_instance = instance
答案 2 :(得分:0)
您可以使用django-model-utils中的FieldTracker:https://django-model-utils.readthedocs.io/en/latest/utilities.html#field-tracker