<p>如果您合理地设计响应格式,那么在Django REST框架中您会发现事情更简单。</p>
<p>目前看来有点模糊,但我建议如下:</p>
<pre><code>{
"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
]
}
</code></pre>
<p>我们可以用三个序列化程序来表达,比如:</p>
<pre><code>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)
</code></pre>
<p><a href="http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects</a></p>
<p>然后,因为我们使用的是多个模型,所以很容易定义自己的自定义视图集,而不是试图将其设置为DRF的magic model viewset类型。<br/>
<a href="http://www.django-rest-framework.org/api-guide/viewsets/#example" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/viewsets/#example</a></p>
<p>首先,我们需要一个对象类型来传递给TimelineSerializer。它应该有两个属性:<code>tweets</code>和<code>articles</code></p>
<pre><code>from collections import namedtuple
Timeline = namedtuple('Timeline', ('tweets', 'articles'))
</code></pre>
<p>然后,我们将定义自定义视图集以获取tweets和文章,实例化Timeline对象并返回TimelineSerializer数据:</p>
<pre><code>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)
</code></pre>