[Answered ]-How do I edit my serializer create() method to make relationship to nested object in Django REST Framework?

1๐Ÿ‘

โœ…

I think you need to upload owner_id if it has only an existing user as the owner.

class GroupSerializer(serializers.ModelSerializer):
    owner = UserSerializer(read_only = True)
    user_id = serializers.IntegerField(write_only = True)

    class Meta:
        model = Group
        fields = ["name", "picture_url", "owner", "members", "user_id"]
    
    def create(self, validated_data):
        user_id = validated_data.pop("user_id")
        try:
            user = User.objects.get(user_id=user_id)
            instance = Group.objects.create(owner = user, **validated_data)
            return instance
        except User.DoesNotExist:
            raise serializers.ValidationError("Invalid user id")

And the payload should be,

{
    "user_id": 6,
    "picture_url":"nothing",
    "name":"jazz club"
}
๐Ÿ‘คMetalgear

Leave a comment