Django Rest Framework 序列化程序不想接受返回的列表,并返回 AttributeError 'str'对象没有属性'x'



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

当运行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",
],
},
]

此处不需要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)
class ProductColorSerializer(serializers.ModelSerializer):
class Meta:
model = ProductColor
fields = '__all__'
class ProductFiltersByCategorySerializer(serializers.ModelSerializer):
"""
A serializer to display available filters for a product lust 
"""
product_color = ProductColorSerializer(many=True)
class Meta:
model = Product
fields = ['product_color']

最新更新