Django RF update_or_create [英] Django RF update_or_create
本文介绍了Django RF update_or_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更新或创建以下模型:
I am trying to update or create the following model:
class Profile(models.Model):
user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE)
canMakeEvent = models.BooleanField(default=False)
与序列化程序:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
并查看:
def post(self, request):
answer, created = Profile.objects.update_or_create(
user=request.user, canMakeEvent = request.data['canMakeEvent'])
return Response()
<我理解响应不正确,但是update_or_create的代码是我主要担心的问题。控制台输出以下内容:
I understand the response isn't correct but the code to update_or_create is what I'm worried about primarily. The console outputs the following:
唯一约束失败:event_profile.user_id
推荐答案
您需要添加 默认值
参数仅按user_id执行搜索,而不按(user_id,canMakeEdit)组合进行搜索:
You need to add defaults
argument to perform search only by user_id not by combination of (user_id, canMakeEdit):
answer, created = Profile.objects.update_or_create(
user=request.user, defaults={'canMakeEvent': request.data['canMakeEvent']})
这将允许更新所选用户的现有个人资料(如果存在)或创建新的个人资料否则。
This will allow to update existing profile of selected user if it exists or create new otherwise.
这篇关于Django RF update_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文