Django - save() update on duplicate key

﹥>﹥吖頭↗ 提交于 2019-11-28 06:53:17

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.

First, you must check if the rating exists. So you may either use what Daniel Roseman said or use exists, but you can not solve this with a simple update since update do not create new records...

rating = 2
rate, created = VideoRate.objects.get_or_create(user_id=1, video_id=1, crit_id=1,
    defaults={'rate':rating})#if create, also save the rate infdormation

if not created:# update
    rate.rate = rating
    rate.save()

You can use defaults to pass exrta arguments, so if it is an insert, database record will be created with all required information and you do not need to update it again...

Documentation

Update: This answer is quite old just like the question. As @peterthomassen mention, Django now have update_or_create() method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!