Search code examples
pythondjangodjango-rest-framework

Inherits help_text from django.db.models.Field in rest_framework.serializer.Field


Let's consider

models.py

class Foo(models.Model):
    ...
    bar = models.IntegerField(help_text='This is bar')
    baz = models.IntegerField(help_text='This is baz')

serializers.py

class FooSerializer(serializers.ModelSerializer):
    bar = serializers.IntegerField(min_value=0, max_value=9)

    class Meta:
        model = Foo
        fields = ('bar', 'baz')

In this example, FooSerializer has two fields:

  • bar: serializers.IntegerField(min_value=0, max_value=9)
  • baz: serializers.IntegerField(label='This is baz'). The label is automatically inherited from the help_text property.

For documentation purposes, i would like to inherits help_text even if i redefine the field. In this case, i have to since i need min/max value for bar. Is there a way to do so?


Solution

  • To inherit the options defined in the model fields in your serializer and add some extra options, you need to use the extra_kwargs option.

    You need a define a dictionary extra_kwargs in your serializer's Meta class. This will allow you to specify arbitrary additional keyword arguments on fields. You will then not need to explicitly declare the field on the serializer.

    The keys of the extra_kwargs dictionary will be the field names for which you want to add some additional arguments and its value will be a dictionary containing those additional keyword arguments.

    serializers.py

    class FooSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Foo
            fields = ('bar', 'baz')
            extra_kwargs = {
                'bar': { # add additional arguments for 'bar' field
                    'min_value':0, # specify 'min_value' argument 
                    'max_value': 9 # specify 'max_value' argument
                }
            }
    

    The above approach will add those additional arguments to the model fields apart from inheriting the default arguments specified in the model.