django-rest-framwork如何返回{[data1,data2]}而不是[data1,data2]

时间:2015-08-06 03:30:08

标签: python django django-rest-framework

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

圆圈就像一个群体。

我收到了以下回复:

[
    {
        "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"
    }
]

但应该是这样的:

{   
    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"
        }
    ]
}

序列化程序:

class CircleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Circle
        fields = ('name', 'avatar', 'desc', 'image', 'created_date')
        read_only_fields = ('created_date',)

CircleViewSet:

class CircleViewSet(NestedViewSetMixin, viewsets.ReadOnlyModelViewSet):
    queryset = Circle.objects.all()
    serializer_class = CircleSerializer
    permission_classes = (permissions.IsAuthenticated,)

和模型:

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)

任何人都有想法?感谢您的回答。

1 个答案:

答案 0 :(得分:0)

您可以通过覆盖序列化程序的to_representation()方法来实现。

根据overriding serialization behaviour:

上的DRF文档
  

如果需要更改序列化,反序列化或验证   一个序列化程序类,你可以通过重写   .to_representation().to_internal_value()方法。

您可以执行以下操作:

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

执行此操作将返回以下内容:

{   
    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"
        }
    ]
}