序列化程序中的循环依赖 [英] Circular dependency in serializers

查看:23
本文介绍了序列化程序中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 django-rest-framework,我会执行以下操作:

I play with django-rest-framework and I would do following:

from rest_framework import serializers

from .models import Author, Book


class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(many=False)

    class Meta:
        model = Book
        fields = ('slug', 'name')


class AuthorSerializer(serializers.ModelSerializer):
    books = BookSerializer(many=True)

    class Meta:
        model = Author
        fields = ('slug', 'name', 'books')

但它失败了.

NameError at /api/books/authors/
name 'AuthorSerializer' is not defined

有人帮忙吗?

推荐答案

当文件被导入时,它的内容是从上到下执行的.所以行 author = AuthorSerializer(many=False) 尝试在定义之前实例化 AuthorSerializer 类.

When the file is imported, it's content is executed from top to bottom. So the line author = AuthorSerializer(many=False) tries to instantiate the AuthorSerializer class before it is defined.

即使你能解决循环依赖问题,这也是糟糕的设计.每当您序列化 Author 时,您都会包含他所有书籍的列表,该列表又包含 Author 对象及其书籍列表.这将导致超出递归深度限制的另一个错误.

Even if you could fix the circular dependency problem, it would be bad design. Whenever you serialize an Author, you include a list of all his books, which in turn include the Author object with it's list of books. This will result in another error for exceeding the recursion depth limit.

您需要决定的是,您希望将包含的序列化保留在哪个方向:您想要每个书籍序列化中的完整 Author 对象,还是想要每个 Author 对象的书籍列表及其所有信息?

What you need to decide is in which direction you want to keep the included serialization: do you want the full Author object in each book serialization, or do you want the list of books with all its information for each Author object?

然后可以使用任何形式的 RelatedField 由 Django REST 框架提供.

The reverse relation can then be included using any form of RelatedField as provided by the Django REST Framework.

这篇关于序列化程序中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆