Issues with OneToOne field in serializer in django rest system

I have a UserProfile model associated with a User model through a one-to-one relationship.

UserProfileSerializer is defined correctly and it serializes userprofile .

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    country = models.CharField(max_length=255)

class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ('user','country')

      

But it gives error {'user': ['This field is required']} when transferring data.

>>> s = UserProfileSerializer(data = {'user':1,'country':'YY'} )

>>> s.is_valid()  
False

>>> s.errrors
{'user':['This field is required']}

      

+3


source to share


1 answer


It might be too late to help, and I'm not really sure what you are trying to do, but try setting the field to a user

field in the serializer to use PrimaryKeyRelatedField

so you can represent a user with an id, or set the field to a user

value readonly

if you want to update UserProfile

things. If you don't want to use a primary key, other relationship fields are here .



If you change the field user

to PrimaryKeyRelatedField and you want the user data to return as it is now, you can make two serializers UserProfile

- one for writes and one for reads. After create

or update

you can switch to the read serializer to populate the answer.

+1


source







All Articles