python - 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",
],
},
]
解决方案
你不需要在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)
推荐阅读
- spring - Spring batch xml repositoryitemwriter 模式占位符表单属性
- python-3.x - 在python中添加变量
- python - re.findall 不符合我所期望的一切
- php - 访问被拒绝 - Laravel/MySQL
- python - 如何使用 Python 写入文本文件,以便我可以在终端/gnuplot 中同时读取它
- java - 如何通过 Self Link 在 Spring Data REST 服务器中加载实体?
- powershell - 如何使用powershell检查下载的文件是否存在
- mysql - SQL:根据其他表列值选择不同的列
- python - 我可以将我的模型连接到外部应用程序吗?
- java - Java:检测服务中注入的过多依赖项