Search code examples
djangodjango-rest-frameworkdjango-serializer

Django REST framework: Serializer to use max_length from model


I have a model

class Person(models.Model):
    name = models.CharField(max_length=254)

and related serializer

class PersonSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=True, max_length=254)

    class Meta:
        model = Person
        fields = ('name',)

Is there a way to make CharField automatically detect max_length from the model and use that in validation?

Using Person._meta.get_field('name').max_length could be an option but feels a bit cumbersome to be used in every field. Maybe overriding CharField with custom implementation? Or is there other options?


Solution

  • If you want to translate a model in a straightforward way to a serializer, you can use a ModelSerializer. You can inject extra parameters to the constructors of the serializer fields with the extra_kwargs field [drf-doc], so:

    class PersonSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Person
            fields = ('name',)
            extra_kwargs = {
                'name': {'required': True}
            }