将APIView与DRF中的非模型字段序列化程序一起使用

时间:2019-06-08 07:05:09

标签: django-rest-framework django-rest-viewsets

我正在研究利用序列化程序通过外部API调用来处理GET / POST请求。 所有这些字段都来自不同的端点,然后需要将它们全部汇总为一个响应。 此数据没有模型,因为我们不需要存储数据-只是从外部API接收并作为汇总提供给前端。 因此,我找不到与我的情况类似的非模型序列化器实现的许多选项,因为大多数答案都涉及类/模型。

# This is a sample data that I get through an external API using the following link: https://example.com/api/books/bk001/authors

{
    "book_id": "bk001",
    "book_authors": {
        "author_1": "John Doe",
        "author_2": "Sarah Brown"
        }           
}

到目前为止,这是我的代码,但是我不确定我是否做对了:

# serializers.py
class BookSerializer(serializers.Serializer):
    book_id = serializers.CharField()
    book_authors = serializers.DictField()

# views.py
class BookView(views.APIView):
    serializer_class = serializers.BookSerializer

    def get(self, request, book_id):        

        book_authors = requests.get(f"https://example.com/api/books/{book_id}/authors").json()
        return Response(book_authors)

在给定的情况下使用它是否正确?

0 个答案:

没有答案
相关问题