Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

Django Rest Framework creatable fields and updatable fields


Below is my sample model:

class DemoModel(models.Model):
    field_one = models.IntegerField()
    field_two = models.IntegerField(blank=True, null=True)

The Serializer:

class DemoSerializer(serializers.ModelSerializer):
    """
    Here only field_one should be creatable and only field_two should be updatable
    """
    class Meta:
        model = models.DemoModel
        fields = '__all__'

My question is how can I write the view for this serializer and model, so that when using the post method the client can not add data for the field_two field. Client can only add data to field_one. But while updating, the client can update the value of field_two, but can not update the value of field_one field.


Solution

  • I have achieve this by overriding the create and update method inside the serializer:

    class DemoSerializer(serializers.ModelSerializer):
        """
        Serializer for DemoModel
        """
        class Meta:
            model = models.DemoModel
            fields = '__all__'
    
        def create(self, validated_data):
            """
            Overriding create method here to preventing some fields from getting created
            """
            validated_data.pop('field_two', None)  # prevent field_two from being created
            return super(LeaveRequestSerializer, self).create(validated_data)
    
        def update(self, instance, validated_data):
            """
            overriding update method here to preventing some fields from getting updated
            """
            validated_data.pop('field_one', None)  # prevent field_one from being updated
            return super(LeaveRequestSerializer, self).update(instance, validated_data)
    
    

    And for the view I used simple genericview