禁止直接分配给多对多集的反面。请改用products.set()。 Django REST框架

时间:2018-11-21 19:36:28

标签: python django django-rest-framework

发布带有类别的新产品时,出现以下错误(产品信息的格式如下:)

{
    "product_code": "testcode",
    "name": "testname",
    "quantity": 22,
    "price": 22,
    "categories": [{
        "name": "Test category",
        "products": [],
        "categories": []
}]
}

错误

Direct assignment to the reverse side of a many-to-many set is prohibited. Use products.set() instead.

当我使用

product.categories.set(**category)

我收到以下错误

set() got an unexpected keyword argument 'name'

我的models.py文件

from django.db import models

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=255)
    categoriesId = models.ForeignKey('self', related_name='categories',on_delete=models.CASCADE, blank=True, null=True)

class Product(models.Model):
    product_code = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    price = models.IntegerField()
    quantity = models.IntegerField()
    categories = models.ManyToManyField(Category, related_name='products')

我的serializers.py文件

from rest_framework import serializers
from products_and_categories.models import Product, Category
from django.db import models


class CategorySerializer(serializers.ModelSerializer):
    def to_representation(self, obj):
        if 'categories' not in self.fields:
            self.fields['categories'] = CategorySerializer(obj, many=True)      
        return super(CategorySerializer, self).to_representation(obj)

    class Meta:
        model = Category
        fields = ("name", 'products', 'categories')

class ProductSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True)
    class Meta:
        model = Product
        fields = ("product_code", "name", "quantity", "price", 'categories')

    def create(self, validated_data):
        category_data = validated_data.pop('categories')
        product = Product.objects.create(**validated_data)
        for category in category_data:
            product.categories.create(**category)
        return product

知道发生了什么吗?

0 个答案:

没有答案