Home > Software design >  Django REST framework: Serializer to use max_length from model
Django REST framework: Serializer to use max_length from model

Time:05-10

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?

CodePudding user response:

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}
        }
  • Related