如何使用Django Rest Framework反序列化嵌套的序列化程序

时间:2018-01-24 21:00:14

标签: python json django serialization django-rest-framework

我有models.py

class Variants(Model):
    class Meta:
        db_table = 'variants'

        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=255, blank=False, null=False)
        client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False, blank=False)
        created_at = models.DateField(auto_created=True, default=now, blank=True)
        updated_at = models.DateField(auto_now=True, null=True, blank=True)

class VariantOptions(Model):
    class Meta:
        db_table = 'variant_options'

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=False, null=False)
    variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False)
    created_at = models.DateField(auto_created=True, default=now, blank=True)
    updated_at = models.DateField(auto_now=True, null=True, blank=True)

和serializers.py

class VariantOptionsSerializer(serializers.ModelSerializer):
class Meta:
    model = models.VariantOptions
    fields = ['name']

class VariantsSerializer(serializers.ModelSerializer):
    options = VariantOptionsSerializer(many=True)

class Meta:
    model = models.Variants
    fields = ['name','client','options']

def create(self, validated_data):
    options_data = validated_data.pop('options')
    variant = models.Variants.objects.create(**validated_data)
    for option_data in options_data:
        models.VariantOptions.objects.create(variant=variant, **option_data)
    return variant

和我的观点

class VariantsCreate(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = serializers.VariantsSerializer
    def post(self, request, format=None):
        serializer = serializers.VariantsSerializer(data=request.data)
        if serializer.is_valid():
            saved = serializer.save()
            return Response(serializer.data) ==> serializer.data gives error
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我有这个错误

  尝试在序列化程序options上获取字段VariantsSerializer的值时,

出现AttributeError。   序列化程序字段可能名称不正确,并且与Variants实例上的任何属性或键都不匹配。   原始例外文字是:'变种'对象没有属性'选项'。

但是已经通过调用is_valid()

验证了数据

为什么return Response(serializer.data)会出错?

1 个答案:

答案 0 :(得分:1)

尝试更改

variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False)

variant = models.ForeignKey(Variants, related_name='options', on_delete=models.CASCADE, null=False, blank=False)