首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何返回{[data1,data2]}而不是[data1,data2] ]

如何返回{[data1,data2]}而不是[data1,data2] ]
EN

Stack Overflow用户
提问于 2015-08-06 03:30:07
回答 1查看 58关注 0票数 0

我在django后端应用程序中使用django rest框架。

一个圆圈就像一个团体。

我得到了以下回报:

代码语言:javascript
运行
复制
[
    {
        "name": "Administrator",
        "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_gnSSWSO.pbm",
        "desc": "the group of administrators",
        "image": null,
        "created_date": "2015-07-31T03:24:21.116000Z"
    },
    {
        "name": "Developer",
        "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_84E7KLC.ppm",
        "desc": "the group of developers",
        "image": null,
        "created_date": "2015-07-31T03:17:59.343000Z"
    }
]

,但应该是这样的:

代码语言:javascript
运行
复制
{   
    circles:[
        {
            "name": "Administrator",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_gnSSWSO.pbm",
            "desc": "the group of administrators",
            "image": null,
            "created_date": "2015-07-31T03:24:21.116000Z"
        },
        {
            "name": "Developer",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_84E7KLC.ppm",
            "desc": "the group of developers",
            "image": null,
            "created_date": "2015-07-31T03:17:59.343000Z"
        }
    ]
}

序列化程序:

代码语言:javascript
运行
复制
class CircleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Circle
        fields = ('name', 'avatar', 'desc', 'image', 'created_date')
        read_only_fields = ('created_date',)

the CircleViewSet:

代码语言:javascript
运行
复制
class CircleViewSet(NestedViewSetMixin, viewsets.ReadOnlyModelViewSet):
    queryset = Circle.objects.all()
    serializer_class = CircleSerializer
    permission_classes = (permissions.IsAuthenticated,)

与模型:

代码语言:javascript
运行
复制
class Circle(models.Model):
    name = models.CharField(max_length=60, unique=True, db_index=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    avatar = models.ImageField(_('Avatar'), upload_to='circle_avatars')
    desc = models.TextField(_('Description'), max_length=560)
    image = models.ImageField(upload_to='circle_images', blank=True)

    CATEGORY_CHOICES = (
        ('C', _("Common")),
        ('B', _("Buddhism")),
    )
    category = models.CharField(_('Category'), choices=CATEGORY_CHOICES, default='C', max_length=2, db_index=True)

    created_date = models.DateTimeField(auto_now_add=True, editable=False)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return "{}".format(self.name)

有人有主意吗?谢谢你的回答。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-06 18:49:45

您可以通过重写序列化程序的to_representation()方法来做到这一点。

根据重写序列化行为:上的DRF文档

如果需要更改序列化程序类的序列化、反序列化或验证,可以通过重写.to_representation().to_internal_value()方法来做到这一点。

你可以这样做:

代码语言:javascript
运行
复制
class CircleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Circle
        fields = ('name', 'avatar', 'desc', 'image', 'created_date')
        read_only_fields = ('created_date',)

    def to_representation(self, obj):
        # call the super() to get the default serialized data
        serialized_data = super(CircleSerializer, self).to_representation(obj) 
        custom_representation = {'circles': serialized_data} # insert the above response in a dictionary
        return custom_representation

这样做会返回如下内容:

代码语言:javascript
运行
复制
{   
    circles:[
        {
            "name": "Administrator",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_gnSSWSO.pbm",
            "desc": "the group of administrators",
            "image": null,
            "created_date": "2015-07-31T03:24:21.116000Z"
        },
        {
            "name": "Developer",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_84E7KLC.ppm",
            "desc": "the group of developers",
            "image": null,
            "created_date": "2015-07-31T03:17:59.343000Z"
        }
    ]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31846335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档