Provide a way to avoid circular import of serializers #7790
Replies: 4 comments 5 replies
-
Hi mrodal! I managed to achieve the same by implementing the following in one of the "circular" serializers: DRF: Reverse relations Though I do think it's quite complex. |
Beta Was this translation helpful? Give feedback.
-
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. |
Beta Was this translation helpful? Give feedback.
-
I'm surprised this does not end up in infinite loop. |
Beta Was this translation helpful? Give feedback.
-
First step to addressing this would be for someone to demo this as a code-snippet or third party package. I suppose that might look something like this?... class LazyRefSerializer(serialisers.BaseSerializer):
def __init__(self, ref):
self._reference_as_string = ref
self._reference_as_serializer = None
def to_representation(self):
if self._reference_as_serializer is None:
# Lazily create a model serializer
model_ref = import_from_string(self._reference_as_string)
class DynamicSerializer(ref):
class Meta:
model = model_ref
self. _reference_as_serializer = DynamicSerializer
return self._reference_as_serializer.to_representation() If anyone wants to expand on that and test it, then we could link to a code snippet or third party package from the docs. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
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
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')
Beta Was this translation helpful? Give feedback.
All reactions