經過幾天的谷歌搜索這個問題的答案,我終於偶然發現this page,這解釋瞭如何做我想做的事情。如果別人有同樣的問題,我在這裏發佈了自己的答案。
這個技術現在看起來很簡單,我明白了,但我很難在網上找到任何描述這種技術的東西。基本上,您將多個查詢集合在一起,然後將鏈轉換爲Python列表。然後迭代列表,手動調用正確的序列化程序,並追加到字典中。然後,您可以將字典轉儲爲JSON。
我已經發布了相關的代碼的情況下,該鏈接去死:
def get_queryset(self):
queryset_a = Post.objects.all()
queryset_b = FriendRequest.objects.filter(is_unanswered=True)
# Create an iterator for the querysets and turn it into a list.
results_list = list(chain(queryset_a, queryset_b))
# Optionally filter based on date, score, etc.
sorted_list = sorted(results_list, key=lambda instance: -instance.date_created)
# Build the list with items based on the FeedItemSerializer fields
results = list()
for entry in sorted_list:
item_type = entry.__class__.__name__.lower()
if isinstance(entry, Post):
serializer = PostSerializer(entry)
if isinstance(entry, FriendRequest):
serializer = FriendRequestSerializer(entry)
results.append({'item_type': item_type, 'data': serializer.data})
return results
的模型是相關的,但一個是不是其他的一個抽象類。基本上,我需要一種方法將兩個QuerySets附加到單個模型,然後序列化整個事物。而且這個單一模型是一個非託管模型(即沒有相應的數據庫表)。基本上我試圖將幾組相關的數據組合在一起。不幸的是,這個建議並沒有太多幫助。 –
我添加了一個鏈接到SO關閉的答案。它只是沒有解釋如何序列化結果,特別是當我序列化的模型不受管理時。 –