Django-rest-framework: Provide a way to avoid circular import of serializers

Created on 18 Jun 2020  ·  3Comments  ·  Source: encode/django-rest-framework

Its a common case where you have modules where both refer to each other.

For example, modules users and posts. On users you have User and on posts you have Post and Attachment

# users
class UserSerializer:
    posts = PostSerializer()
    profile_attachments = AttachmentSerializer()


#posts
class PostSerializer:
    user = StringSerializer()
    attachments = AttachmentSerializer()

class AttachmentSerializer:
    name = CharField()
    size = IntegerField()

In Django there's a way to declare Foreign Keys that avoids circular dependencies, declaring the referenced model by a string:

profile_attachment = models.ForeignKey('posts.Attachment', on_delete=models.CASCADE)

Could DRF offer something like that for serializers? Something like

profile_attachment = ModelSerializer(serializer='posts.AttachmentSerializer')

All 3 comments

Hi mrodal!

I managed to achieve the same by implementing the following in one of the "circular" serializers: DRF: Reverse relations
Django: Following relationships “backward”

Though I do think it's quite complex.

So i actually have the same case in a project i work on, but you really shouldn't. best practice, from a software engineering and architecture course is to have a one way dependency. If possible atleast. If there is a very close coupling between the two apps they should maybe be one app, alternatively they should have a common parent. You could also move your serializer into a sub-app if applicable.

I might be wrong, but AFAIK that is best practice.

I'm surprised this does not end up in infinite loop.

Was this page helpful?
0 / 5 - 0 ratings