0

I'm new to Django rest framework serializers.

I have this serializer that I use for GET requests.

class MemberChargeSerializer(serializers.ModelSerializer):

    chargeTypeName = serializers.CharField(
        source='chargeType.memberChargeTypeName',
        read_only=True)
    firstName = serializers.CharField(
    source='user.first_name',
    read_only=True)

    lastName = serializers.CharField(
        source='user.last_name',
        read_only=True)

    class Meta:
        model = MemberCharge
        fields = ('id', 'chargeTypeName', 'firstName', 'lastName', 'amount',
        'amountPaid', 'fullyPaid', 'date', 'void')

It works well. Now, I need to do something to handle a POST request. I will not submit the following fields: id, firstName, lastName, fullyPaid in the request.data. I was thinking about implementing another serializer to handle my POST requests. Is it the right way to do this? Keep in mind that I will submit other fields and not use certain ones.

Thank you.

1 Answer 1

3

The serializer can be used for both the get and post request.It basically depends on the model fields options.

For using only the fields "id", "firstName", "lastName", "fullyPaid" for post request , your other fields must be optional, then only you will be able to call satisfy is_valid method of the serializer.

Eg.

for other fields use blank = True, which will make the fields optional

chargeTypeName = models.CharField(max_length=6, blank=True)
Sign up to request clarification or add additional context in comments.

3 Comments

I added blank=True parameter and when I try to retrieve the an object or a collection of objects on my browser I get this error: __init__() got an unexpected keyword argument 'blank'
I entered that parameter in the serializer, it should be in the model. So, what matters is what is how the model is defined to either validate or invalidate the data going in the serializer.
you can also add additional custom validation by overriding the is_valid function of the serializer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.