Custom JSON representation of query result

此生再无相见时 提交于 2020-01-15 20:59:25

问题


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.

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?


回答1:


I hope this helps... (Django 1.8)

Model:

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)

Serializer:

    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')

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




回答2:


One way to do this is by overriding the to_representation method in serializers.ListSerializer.

class CustomListSerializer(serializers.ListSerializer):

    def to_representation(self, instances):
        data = []
        for instance in instances:
            field1 = instance.field1
            field2 = instance.field2
            data.append({'field1':field1,'field2':field2})
        return data

class YourSerializer(serializers.ModelSerializer):

    class Meta:
        model = YourModel
        list_serializer_class = CustomListSerializer

to_representation method in serializers.ListSerializer converts List of object instances to List of dicts of primitive datatypes.

I have just shown you an example of what can be done. You can modify the to_representation to your requirement. Just make sure your dictionaries are inside a list.




回答3:


As far as I know you don't need any hook, DRF has default support for nested results, you need just to use the right serializer class based on the relation between the models and how you want it to be displayed.

class ModelASerializer(serializers.ModelSerilizer):
      modelb = ModelBSerializer(many=True) # case many to many realtionship

oder

      modelb = ModelBSerializer(read_only=True) # case foreign key

so based on your needs you can format your response using serializers, there is also serializers.DictField, serializers.ListField for field serialization.

Check Model Serializer, Field Serializer



来源:https://stackoverflow.com/questions/34201168/custom-json-representation-of-query-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!