1

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?

3
  • 4
    Use a ModelSerializer, and let Django convert the fields to their serializer field counterparts. Commented May 9, 2022 at 9:51
  • This seems to work fine when fields are just declared in Meta section. But if there is a need to add custom arguments to fields, then e.g. max_length is not transferred from model. For example name = serializers.CharField(required=True) doesn't use max_length validation Commented May 9, 2022 at 10:19
  • You can use extra_kwargs to inject extra parameters: django-rest-framework.org/api-guide/serializers/… Commented May 9, 2022 at 10:36

1 Answer 1

1

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}
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.