Serialize multiple models and send all in one json response django rest framework

前端 未结 2 1470
故里飘歌
故里飘歌 2020-12-08 12:05

This question is being asked to expand and fill in the holes from this one: Return results from multiple models with Django REST Framework

my goal is to return a jso

2条回答
  •  暖寄归人
    2020-12-08 12:41

    You'll find things easier in Django REST Framework if you design your response format rationally.

    It seems a bit vague at the moment, but I would suggest something like:

    {
        "tweets": [
            {"tweet_attr_A": value_1, ...},  // first tweet
            {"tweet_attr_A": value_2, ...},  // second tweet
            //etc
        ],
        "articles": [
            {"id": 1, ...},  // first article
            {"id": 2, ...},  // second article
            //etc
        ]
    }
    

    We can express this with three serializers, like:

    class TweetSerializer(serializers.ModelSerializer):
        class Meta:
            model = Tweet
    
    class ArticleSerializer(serializers.ModelSerializer):
        class Meta:
            model = Article
    
    class TimelineSerializer(serializers.Serializer):
        tweets = TweetSerializer(many=True)
        articles = ArticleSerializer(many=True)
    

    http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

    Then, because we're using more than one model, it's easiest just to define your own custom viewset rather than trying to shoe-horn this into DRF's magic ModelViewSet type.
    http://www.django-rest-framework.org/api-guide/viewsets/#example

    First we need an object type to pass into our TimelineSerializer. It should have two attributes: tweets and articles

    from collections import namedtuple
    
    Timeline = namedtuple('Timeline', ('tweets', 'articles'))
    

    Then we'll define the custom viewset to fetch the tweets and articles, instantiate a Timeline object and return the TimelineSerializer data:

    class TimelineViewSet(viewsets.ViewSet):
        """
        A simple ViewSet for listing the Tweets and Articles in your Timeline.
        """
        def list(self, request):
            timeline = Timeline(
                tweets=Tweet.objects.all(),
                articles=Article.objects.all(),
            )
            serializer = TimelineSerializer(timeline)
            return Response(serializer.data)
    

提交回复
热议问题