Django - save() update on duplicate key

前端 未结 2 1963
予麋鹿
予麋鹿 2020-12-08 20:16

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.

But he should be a

2条回答
  •  甜味超标
    2020-12-08 20:39

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

    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.

提交回复
热议问题