如何继承序列化器字段上的源字段验证器?

时间:2019-09-04 02:25:23

标签: python django django-rest-framework

说我有以下模型:

from django.db import models
class MyModel(models.Model):
    my_field = models.CharField(max_length=5, unique=True)

当我创建ModelSerializer并在Meta类上定义模型字段时,它会自动定义序列化器字段,如下所示:

from rest_framework import serializers
class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('my_field',)

>>> MySerializer()
MySerializer():
    my_field = CharField(max_length=5, validators=[<UniqueValidator(queryset=MyModel.objects.all())>]

但是,如果我在序列化程序上重新定义此字段-例如说我想重命名此字段以符合API规范-它按如下定义(如预期):

from rest_framework import serializers
class MyOtherSerializer(serializers.ModelSerializer):
    my_other_field = serializers.CharField(source="my_field")
    class Meta:
        model = MyModel
        fields = ('my_other_field',)

>>> MyOtherSerializer()
MyOtherSerializer():
    my_other_field = CharField(source='my_field')

如何在序列化器字段上从max_length指定的模型字段中继承validatorssource?有办法吗?

我知道我可以通过在序列化器字段上指定max_lengthvalidators重新定义它们,但我希望避免重复代码。

0 个答案:

没有答案