Adding extra data to Django Rest Framework results for entire result set

后端 未结 4 1334
刺人心
刺人心 2020-12-14 15:42

I\'m using Django Rest Framework and need to add extra data to a result set. Specifically, where you would usually have:

{
    \"count\": 45, 
    \"next\":          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 16:03

    Use SerializerMethodField as mentioned in this solution.

    It can be used to add any sort of data to the serialized representation of your object. (REST framework doc)

    Example from the documentation:

    from django.contrib.auth.models import User
    from django.utils.timezone import now
    from rest_framework import serializers
    
    class UserSerializer(serializers.ModelSerializer):
        days_since_joined = serializers.SerializerMethodField()
    
        class Meta:
            model = User
    
        def get_days_since_joined(self, obj):
            return (now() - obj.date_joined).days
    

提交回复
热议问题