Django REST Serializer Method Writable Field

I am reading the Django REST Framework, and I have a model that is serialized using getters using SerializerMethodField () .

However, when I send POST to this endpoint, I also want to set this field, but this does not work, because, as shown above, you cannot write to SerializerMethodField. Is there a way in Django REST to have a serializer field for which you define a custom getter method and a custom label method?

EDIT: Here is the source of what I'm trying to do. The client has a 1 to 1 relationship with the user.

class ClientSerializer(serializers.ModelSerializer): email = serializers.SerializerMethodField() def create(self, validated_data): email = validated_data.get("email", None) # This doesn't work because email isn't passed into validated_data because it a readonly field # create the client and associated user here def get_email(self, obj): return obj.user.email class Meta: model = Client fields = ( "id", "email", ) 
+5
source share
2 answers

You need to use a different type of field:

 class ClientSerializer(serializers.ModelSerializer): email = serializers.EmailField(source='user.email') def create(self, validated_data): # DRF will create object {"user": {"email": "inputed_value"}} in validated_date email = validated_data.get("user", {}).get('email') class Meta: model = Client fields = ( "id", "email", ) 
+1
source

Why not just create a client in the view?

 def post(self, request, *args, **kwargs): data = { 'email': request.data.get('email'), } serializer = ClientSerializer(data=data) if serializer.is_valid(): email = serializer.data.get('email') client = Client.objects.create(email=email) # do other stuff 
0
source

Source: https://habr.com/ru/post/1259607/


All Articles