asus1902 asus1902 - 1 year ago 195
Python Question

Django rest framework one to one relation Create serializer

I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me

class Account(models.Model):


class AccountCreateUpdateSerializer(serializers.ModelSerializer):


class Meta:
model= Account
def create(self,validated_data):

return account

the error :
enter image description here

Answer Source

Your problem is here:

   user_data = validated_data.pop('user')
   account = Account.objects.create(**validated_data)
   User.objects.create(account=account, **user_data)

You're trying to create an Account before creating a User, which won't work because an Account requires a value for user_id. If your User model had a foreign key to Account, instead of the other way around, then creating the account first would be the right way to do it.

Switching to:

   user_data = validated_data.pop('user')
   user = User.objects.create(**user_data)
   account = Account.objects.create(user=user, **validated_data)

should fix the problem as long as your UserListSerializers() is providing the correct data to create a User instance.

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download