根据值分组序列化器结果

根据值分组序列化器结果

本文介绍了根据值分组序列化器结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,因此无法使用基于类的视图来判断是否可行,但是我想根据查询返回的JSON中的值对搜索结果进行分组。基本上,我希望结果来自于此:

I'm fairly new to Django, so I can't tell if this is possible using a class based view, but I would like to group search results based on a value in the JSON returned from the query. Basically I want my results to go from this:

{
"id": "0038",
"attributes": [
    {
        "name": "State",
        "values": "CA"
    },
    {
        "name": "Areas",
        "values": "Value 1"
    },
    {
        "name": "Areas",
        "values": "Value 2"
    },
    {
        "name": "Areas",
        "values": "Value 3"
    }]}

为此:

{"id": "0038",
"attributes": [
    {
        "name": "State Licenses",
        "values": "CA"
    },
    {
        "name": "Areas",
        "values": ["Value 1", "Value 2", "Value 3"]
    }]}

每个名称/值对在MySQL数据库中都是单独的一行。我的models.py看起来像这样:

Each "name/values" pair is a separate row in a MySQL database. My models.py looks like:

class Attribute(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=45, blank=False)
    value = models.CharField(max_length=255, blank=False)

虽然序列化程序看起来像:

While the serializer looks like:

class AttributeSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='name')
    values = serializers.CharField(source='value')
    class Meta:
        model = models.Attribute
        fields= ('name','values')

任何想法我该怎么做? ListSerializer似乎很可能是候选对象,并且通过扩展,添加 many = True 也是如此,但是我认为这不能提供我想要的分组行为。有任何想法吗?

Any idea how I can do that? ListSerializer seems like it might be a likely candidate, and by extension so does adding many=True but I don't think that provides the grouping behavior I want. Any ideas?

推荐答案

您需要覆盖 ListSerializer.to_representation 。阅读.to_representation 的更多信息。 -usage rel = nofollow>文档。

You need to override the ListSerializer.to_representation. Read more about overriding .to_representation in the docs.

def transform_data(data):
    result = {}
    for item in data:
        name, value = item['name'], item['value']
        if result.get(name):
            result[name].append(value)
        else:
            result[name] = [value]
    return result


class AttributeListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        data = super(AttributeListSerializer, self).to_representation(data)
        # data is currently in this format:
        # [
        #     {"name": "State", "values": "CA"},
        #     {"name": "Areas", "values": "1"},
        # ]
        # transform_data can be updated to transform the data however you like...
        return transform_data(data)


class AttributeSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='name')
    values = serializers.CharField(source='value')
    class Meta:
        model = models.Attribute
        fields= ('name','values')
        # the below is KEY
        list_serializer_class = AttributeListSerializer

这篇关于根据值分组序列化器结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:50