Reputation: 146
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)
with the serializer:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
and view:
def post(self, request):
answer, created = Profile.objects.update_or_create(
user=request.user, canMakeEvent = request.data['canMakeEvent'])
return Response()
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:
UNIQUE constraint failed: event_profile.user_id
Upvotes: 1
Views: 551
Reputation: 47354
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.
Upvotes: 2