首页 > 解决方案 > Django Rest Framework Serializer 不想接受返回的列表,并返回 AttributeError 'str' object has no attribute 'x'

问题描述

所以我试图聚合一个颜色列表并将查询集返回给序列化程序,但是由于某种原因,serialzier 似乎不接受这个。

在 shell 中运行命令时,我得到:

>>> from django.contrib.postgres.aggregates import ArrayAgg
>>> from inventory.models import Product
>>> products = Product.objects.filter(category__parent__name__iexact='fliser').distinct().aggregate(colors_field=ArrayAgg('colors__name'))
>>> print(products)
{'colors_field': ['Beige', 'Grå', 'Hvit', 'Sort', 'Beige', 'Gul', 'Rød']}

这是预期的结果。

序列化器的结构如下:

class ProductFiltersByCategorySerializer(serializers.ModelSerializer):
    """
    A serializer to display available filters for a product lust 
    """

    colors = serializers.StringRelatedField(read_only=True, many=True)

    class Meta:
        model = Product
        fields = ['colors']

视图集如下所示:

class ProductFiltersByCategory(generics.ListAPIView):
    """
    This viewset takes the category parameter from the url and returns related product filters
    """

    serializer_class = ProductFiltersByCategorySerializer

    def get_queryset(self):
        category = self.kwargs['category']
        queryset = Product.objects.filter(category__parent__name__iexact=category).distinct().aggregate(colors_field=ArrayAgg('colors__name'))
        return queryset

模型的相关部分如下所示:

class Product(models.Model):

    ...
    colors = models.ManyToManyField(
        ProductColor,
        related_name='product_color'
    )
    ...

尝试访问端点时的错误是'str' object has no attribute 'colors'

期望输出:

[
    {
        "colors": [
            "Red",
            "Orange",
        ],
    },
]

标签: pythondjangodjango-rest-frameworkdjango-serializer

解决方案


你不需要在ListAPIView这里上课,APIView用作

from rest_framework.views import APIView
from rest_framework.response import Response


class MyAPIView(APIView):
    def get(self, request, *args, **kwargs):
        category = kwargs['category']
        agg_result = Product.objects.filter(
            category__parent__name__iexact=category
        ).distinct().aggregate(colors_field=ArrayAgg('colors__name'))
        return Response(agg_result)

推荐阅读