asus1902 asus1902 - 2 months ago 35
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

models.py

class Account(models.Model):

user=models.OneToOneField(User,on_delete=models.CASCADE)
image=models.ImageField(upload_to='Images/',default='Images/user.png')
date=models.DateField(auto_now=True,auto_now_add=False)


Serializers.py

class AccountCreateUpdateSerializer(serializers.ModelSerializer):


user=UserListSerializers()
image=serializers.ImageField()

class Meta:
model= Account
fields=['id','user','image']
def create(self,validated_data):
user_data=validated_data.pop('user')
account=Account.objects.create(**validated_data)
User.objects.create(account=account,**user_data)

return account


the error :
enter image description here

Answer

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.