Django - 在重复键上保存()更新 [英] Django - save() update on duplicate key
问题描述
我没有什么应用程序允许用户对视频进行评分。
I have little application which allows a user to rate a video.
用户只能评价一次。
所以我已经定义了模型的唯一性。
The user can rate only once. So I have defined the uniqueness on the model.
但他应该能够改变他的利率。
所以 save()
应该在重复键上更新
But he should be able change his rate.
So the save()
should update on duplicate key
class VideoRate(models.Model):
"""Users can Rate each Video on the criterias defined for the topic"""
user = models.ForeignKey(User)
video = models.ForeignKey(VideoFile)
crit = models.ForeignKey(VideoCrit)
rate = models.DecimalField(max_digits=2, decimal_places=1, choices=RATE_CHOICES)
class Meta:
unique_together = (('user', 'video', 'crit'),)
verbose_name = 'Video Rating'
如果我
rate = VideoRate(user_id=1, video_id=1, crit_id=1, rate=2)
rate.save()
保存评级,但如果我
rate = VideoRate(user_id=1, video_id=1, crit_id=1, rate=3)
rate.save()
我得到正常错误
IntegrityError: (1062, "Duplicate entry '1-1-1' for key 'user_id'")
即使我使用 force_update = True
(仅基于主键)
Even if I use force_update=True
(since based only on primary keys)
有没有办法更新评级,如果它已经存在,而不必先检查数据?
Is there a way to update the rating if it already exists without having to check data before ?
推荐答案
要更新现有评分,您实际上必须拥有要更新的评分。如果您知道该对象可能不存在,请使用 get_or_create
:
To update an existing rating, you actually have to have the one you want to update. If you know the object may not exist, use get_or_create
:
rate, created = VideoRate.objects.get_or_create(user_id=1, video_id=1, crit_id=1)
rate.rate = 2
rate.save()
您可以使用 update()
来简化此过程:
You can short-cut the process by using update()
:
VideoRate.objects.filter(user_id=1, video_id=1, crit_id=1).update(rate=2)
但是,如果评分不存在,这将无声无效 - 它不会创建一个。
But this will silently fail if the rating does not exist - it won't create one.
这篇关于Django - 在重复键上保存()更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!