Django Rest Framework如何使用Related Field保存manyToMany

时间:2017-11-01 18:54:39

标签: django django-rest-framework

我在Django Rest Framework和manyToMany与Related Field的关系方面遇到了一些问题。当我列出时我有一个错误,当我保存时,它会填充database中的数据,但它无法显示结果。

我的model.py

class Product(models.Model):
    name = models.CharField(max_length=100,unique=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=9,decimal_places=3)
    created = models.DateTimeField(auto_now_add=True)
    edited = models.DateTimeField(auto_now_add=True)
    state = models.ForeignKey('ProductState', default=1)
    tax = models.ForeignKey('Tax')
    categories = models.ManyToManyField('ProductCategory')

class OrderProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    qty = models.IntegerField()
    tax = models.ForeignKey('Tax')

class Order(models.Model):
    ref = models.CharField(max_length=100,blank=True)
    created = models.DateTimeField(auto_now_add=True)
    state = models.ForeignKey('OrderState')
    user = models.ForeignKey(User)
    orderproducts = models.ManyToManyField(Product, through='OrderProduct')

我的serializer.py

class OrderProductSerializer(serializers.ModelSerializer):
    product = ProductSerializer(required=True)

    class Meta:
        model = OrderProduct
        exclude = ()
        read_only_fields = ('order','tax',)

    def create(self, validated_data):
        product = validated_data.pop('product')
        return OrderProduct.objects.create(tax=product['product'].tax, **product)

class OrderSerializer(serializers.ModelSerializer):
    orderproducts = OrderProductSerializer(many=True, required=True)
    def create(self, validated_data):
        products = validated_data.pop('orderproduct')
        order = Order.objects.create(**validated_data)
        for product in products:
            op = OrderProduct.objects.create(product=product['product'], tax=product['product'].tax, order=order, qty=product['qty'] )
            op.save()
        order.save()
        return order;

    class Meta:
        model = Order
        exclude = ()
        read_only_fields = ()

class ProductSerializer(serializers.ModelSerializer):
    categories = ProductCategorySerializer(many=True, required=True)
    tax = TaxSerializer(many=False, required=True)
    state = OrderStateSerializer(many=False, required=False)
    class Meta:
        model = Product
        exclude = ()

和我的view.py

class ClientOrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

当我尝试列出时,我收到此错误:

  

异常类型:/ api / order /的AttributeError       异常值:尝试在序列化程序product上获取字段OrderProductSerializer的值时获得AttributeError。       序列化程序字段可能名称不正确,并且与Product实例上的任何属性或键都不匹配。       原始例外文字是:'产品'对象没有属性' product'。       索取信息:

0 个答案:

没有答案