model:

class Profile(models.Model):
    user       = models.ForeignKey(User)
    occupation = models.CharField()

serializer:

class ProfileSerializer(serializers.ModelSerializer):
    user_id         = serializers.UUIDField(source="user.id")
    user_email      = serializers.EmailField(source="user.email", read_only=True)
    user            = serializers.UserSerializer(read_only=True)

    class Meta:
        model = Profile

It works fine as expected when I hit the API with retrieve action i.e, /profiles/1/

sample response:

{
    "user_id": "user_1",
    "user_email": "[email protected]",
    "occupation": "software engineer",
    "user": {
         "id": "user_1", "first_name": "", ....
    }
}

but when I try to create a resource by providing data as following:

{
    "user_id": "user_2",
    "occupation": "network engineer"
}

the user_id field becomes to this {"user": {"uuid": "requested_user_id"}} on server side such as following:

{
    "user": {
        "uuid": "user_2"
    },
    "occupation": "network engineer",
}

instead of

{
    "user_id": "user_2",
    "occupation": "network engineer",
}

I debugged this by logging serializer.validated_data.

Is this desired behavior or not, from DRF standpoint of view? Is there any simple way to prevent this to happen? (like extra arg in fields that don't change the original defined field name)

I looked at the core arguments in the documentation but didn't find anything helpful.

I simply want to target the user_id in create action under a viewset.

Thanks.

1 Answers

0
JPG On

Change your serializer as below,

class ProfileSerializer(serializers.ModelSerializer):
    user_id = serializers.UUIDField(source="user.id", read_only=True)
    user_email = serializers.EmailField(source="user.email", read_only=True)

    class Meta:
        model = Profile
        fields = '__all__'
        extra_kwargs = {
            'user': {'write_only': True},
        }

and change the creation payload as,

{
    "user": 1,
    "occupation": "network engineer"
}

Where "1" is the PK value of User object in DB.