连接嵌套模型django rest framework API serializer

时间:2018-04-08 08:07:23

标签: django rest api django-models django-rest-framework

我想实现这一目标:获取类别所有产品的API。

Models.py

class Category(models.Model):
    main_category = models.CharField(max_length=200, default = '')

    def __str__(self):
        return '%s' % (self.main_category)

class Subcategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    sub_category = models.CharField(max_length=200, default = '')

    def __str__(self):
        return '%s' % (self.sub_category)

class Products(models.Model):
    sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE)
    product_name = models.CharField(max_length=200, default = '')

    def __str__(self):
        return '%s' % (self.product_name)

Views.py

class ProductCategoryFilter(django_filters.FilterSet):
    category = django_filters.CharFilter(name="category__main_category")

    class Meta:
        model = Products
        fields = ['category']

class ProductCategoryListAPIView(ListAPIView):

    queryset = Products.objects.all()
    serializer_class = ProductCategorySerializer
    filter_class = ProductCategoryFilter

Serializers.py

class ProductCategorySerializer(ModelSerializer):

    #category_name = serializers.CharField(source='category.main_category')
    category_name = CategorySerializer(source='category_set')
    class Meta:
        model = Products
        fields = [
        'category_name',
        'product_name',
        ]

/ api / productcategories /

中的AttributeError

尝试在序列化程序AttributeError上获取字段category_name的值时,我得到ProductCategorySerializer。序列化程序字段可能名称不正确,并且与Products实例上的任何属性或键都不匹配。

原始例外文字是:'产品'对象没有属性'类别'。

我希望输出如下:

[
{
    "category_name": "main category 1",
    "product_name": "product 1"
},
{
    "category_name": "main category 1",
    "product_name": "product 2"
},..........

OR输出如下:

[
{
   "main category 1" :{ "product 1", "product 2"...}

0 个答案:

没有答案