Circular dependency in serializers

前端 未结 3 1736
有刺的猬
有刺的猬 2020-12-25 13:14

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

from rest_framework import serializers

from .models import Author, Book


class BookSerializer(s         


        
3条回答
  •  被撕碎了的回忆
    2020-12-25 13:32

    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.

    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.

    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?

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

提交回复
热议问题