TCFDS
TCFDS

Reputation: 622

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?

Upvotes: 1

Views: 2748

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476739

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

Upvotes: 1

Related Questions