Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Primary Key In a Serializer in Django

My Model is

class UserInfo(models.Model):
    user = models.OneToOneField(User, unique=True)
    mobile_no = models.CharField(max_length=10, blank=True)

and serialzer is :

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ('mobile_no','user')

but whenever I tried to use this

serializer = UserInfoSerializer(data=data)
if serializer.is_valid():
   serializer.save()

It is not saving the data and giving errors.

Is there any method to use other then this to for using Primary key.

like image 276
Ashish Kumar Verma Avatar asked Feb 07 '23 18:02

Ashish Kumar Verma


1 Answers

You should use PrimaryKeyRelatedField

add this to your serializer

user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

Your UserInfoSerializer should look like:

class UserInfoSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model = UserInfo
        fields = ('mobile_no','user')

Update If you want to update existing object in database then you have to pass model instance as an argument to UserInfoSerializer constructor.

user_info = self.get_object()
serializer = UserInfoSerializer(user_info, data=data)
like image 153
Mushahid Khan Avatar answered Feb 09 '23 11:02

Mushahid Khan