Django - save() 更新重复键 [英] Django - save() update on duplicate key

查看:52
本文介绍了Django - save() 更新重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小应用程序可以让用户给视频评分.

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()

它正在保存评分,但如果我

It's saving the rating, but if I

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 - save() 更新重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆