问题描述
我玩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.
这篇关于序列化程序中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!