Django Rest Framework Serializer不想接受返回的列表,并且返回AttributeError'str'对象没有属性'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",],},]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)