说我有以下模型:
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
指定的模型字段中继承validators
和source
?有办法吗?
我知道我可以通过在序列化器字段上指定max_length
和validators
重新定义它们,但我希望避免重复代码。