我有一个具有唯一name
字段的序列化程序:
class ProductTypeSerializer(serializers.ModelSerializer):
url = serializers.URLField(source='get_absolute_url', read_only=True)
id = serializers.IntegerField(required=False)
name = serializers.CharField(validators=[
UniqueValidator(queryset=ProductType.objects.all())
])
user = UserSerializer(required=False)
publish = serializers.BooleanField(required=False)
class Meta:
model = ProductType
fields = ('url',
'id',
'name',
'publish',
'user',
'register_date')
另一方面,还有另一个序列化程序与序列化程序具有多对多关系,具有唯一的名称字段:
class BrandSerializer(serializers.ModelSerializer):
url = serializers.URLField(source='get_absolute_url', read_only=True)
id = serializers.IntegerField(required=False)
name = serializers.CharField()
product_types = ProductTypeSerializer(many=True, required=False)
user = UserSerializer(required=False)
class Meta:
model = Brand
fields = ('url',
'id',
'name',
'product_types',
'publish',
'user',
'register_date')
def create(self, validated_data):
print 'validated_data:', validated_data
request = self.context['request']
name = validated_data.get('name', None)
publish = validated_data.get('publish', False)
product_types_data = validated_data.pop('product_types', None)
product_types = []
for pt in product_types_data:
product_type = ProductType.objects.get(pk=pt['id'])
product_types.append(product_type)
obj = Brand.objects.create(
name=name,
publish=publish,
user=request.user
)
obj.product_types.add(*product_types)
return obj
当我使用BrandSerializer
发布品牌数据时,我收到了一个独特的验证错误:
{"product_types":[{"name":["This field must be unique."]}]}
如何在使用ProductTypeSerializer
创建品牌时取消BrandSerializer
的验证?
答案 0 :(得分:1)
将您的product_type
字段设置为read_only
字段并创建它,从request.data
获取数据而不是validated data
class BrandSerializer(serializers.ModelSerializer):
url = serializers.URLField(source='get_absolute_url', read_only=True)
id = serializers.IntegerField(required=False)
name = serializers.CharField()
product_types = ProductTypeSerializer(many=True, read_only=True)
user = UserSerializer(required=False)
class Meta:
model = Brand
fields = ('url',
'id',
'name',
'product_types',
'publish',
'user',
'register_date')
def create(self, validated_data):
print 'validated_data:', validated_data
request = self.context['request']
name = validated_data.get('name', None)
publish = validated_data.get('publish', False)
product_types_data = request.data.get('product_types', None)
product_types = []
for pt in product_types_data:
product_type = ProductType.objects.get(pk=pt['id'])
product_types.append(product_type)
obj = Brand.objects.create(
name=name,
publish=publish,
user=request.user
)
obj.product_types.add(*product_types)
return obj
如果您想验证product_type是否作为请求中的参数传递,您可以在clean
方法