查询结果的自定义JSON表示形式 [英] Custom JSON representation of query result

查看:45
本文介绍了查询结果的自定义JSON表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django REST Framework中找到想要以特定方式格式化查询结果的位置。

I'm looking for the place in Django REST Framework to hook in when wanting to format the result of a query in a specific way.

即,我想要获取查询返回的所有行,并创建具有某些元数据和不同(嵌套)结构的非常特定类型的JSON响应。

That is, I want to take all the rows returned by a query and create a very specific type of JSON response with some meta data and a different (nested) structure.

似乎序列化程序一次只照顾一排。自定义视图是否合适?

It seems that serializers take care of one row at a time. Are custom views the right place for this?

推荐答案

我希望这会有所帮助...(Django 1.8)

I hope this helps... (Django 1.8)

模型:

class Users(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=100, blank=True)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    company = models.ForeignKey(Company)

序列化器:

    class UserListSerializer(serializers.ModelSerializer):
        company_name = serializers.SerializerMethodField()
        def get_company_name(self, obj):
            return obj.company.name

        class Meta:
            model = Users
            fields = ('id', 'email', 'username', 'first_name', 'last_name',
                     'company_name','company')

使用SerializerMethodField可以为记录添加任何自定义值。您可以使用此方法修改序列化程序。

With SerializerMethodField you can add any custom value for your record. You can modify your serializer with this method.

这篇关于查询结果的自定义JSON表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆