想要使用modelserializer在django rest api中输出字典列表作为单个字典

时间:2017-11-29 12:10:28

标签: django rest pycharm

from rest_framework import serializers
from .models import NewsFeed

class NewsFeedSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = NewsFeed
        fields = ('title', 'description', 'image', 'source_url','source_name','metadata','created_date')

返回 This is what is returned 虽然我想要enter image description here

注意如何将字典列表作为单个字典发送到" feeds"。

2 个答案:

答案 0 :(得分:0)

我的接近是覆盖to_representation的{​​{1}}方法。以下是ModelSerializer

上的添加方法
NewsFeedSerializer

答案 1 :(得分:0)

不幸的是,已接受的答案对我不起作用,所以我认为我应该发表如何解决此问题的信息。我想将与外键相关的模型实例的字典列表更改为单个字典。

Model.py

class DataSet(models.Model):
    # chart = models.OneToOneField(Chart, on_delete='CASCADE')
    title = models.CharField(max_length=20)

    def __str__(self):
        return '{}'.format(self.title)


class Entry(models.Model):
    data_set = models.ForeignKey(DataSet, on_delete='CASCADE')
    key = models.CharField(max_length=20)
    value = models.IntegerField()

    def __str__(self):
        return '{}: {}  {}'.format(self.data_set.title, self.key, self.value)

原始Serializers.py

class EntrySerializer(serializers.ModelSerializer):

    class Meta:
        model = Entry
        fields = '__all__'


class DataSetSerializer(serializers.ModelSerializer):

    entry_set = EntrySerializer(many=True)

    class Meta:
        model = DataSet
        fields = '__all__'

API输出

{
    "id": 1,
    "entry_set": [
        {
            "id": 1,
            "key": "sum_cc",
            "value": 100,
            "data_set": 1
        },
        {
            "id": 2,
            "key": "sum_cm",
            "value": 80,
            "data_set": 1
        },
        {
            "id": 3,
            "key": "sum_dp",
            "value": 75,
            "data_set": 1
        }
    ],
    "title": "Dataset 1"
},

我用以下内容替换了entry_set = EntrySerializer(many=True)中的行DataSetSerializer

entries = serializers.SerializerMethodField()
def get_entries(self, obj):
    return {d.key: d.value for d in obj.entry_set.all()}

,输出为:

{
    "id": 1,
    "entries": {
        "sum_cc": 100,
        "sum_cm": 80,
        "sum_dp": 75
    },
    "title": "Dataset 1"
},

希望它可以帮助遇到相同问题的其他人