许多关系中的唯一验证错误

时间:2016-08-10 16:47:40

标签: django validation many-to-many django-rest-framework unique

我有一个具有唯一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的验证?

1 个答案:

答案 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方法

上执行此操作