Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to make circular imports for included fields #1123

Answered by sliverc
Nekidev asked this question in Q&A
Discussion options

I have the following serializers:

# Module 1
from artist.serializers import ArtistSerializer
class ImageSerializer(serializers.ModelSerializer):
 included_serializers = {
 "artist": ArtistSerializer
 }
 class Meta:
 model = Image
 fields = ["artist"]
# Module 2
from image.serializers import ImageSerializer
class ArtistSerializer(serializers.ModelSerializer):
 included_serializers = {
 "images": ImageSerializer
 }
 class Meta:
 model = Artist
 fields = ["images"]

The images field is a reverse relationship.

This raises a circular dependendy error. I have already tried importing the serializers from inside of the class, but this does not work because when one class is imported, the circular dependency problem starts again. Is there any way that this can be done without importing the serializers to each module? I cannot move the 2 serializers to the same module to fix the error since they need to be in their own apps. Is this impossible?

You must be logged in to vote

Hi @Nekidev. This is a good question. Django REST framework JSON:API supports dotted import string to define included serializers.

This could look something likes this:

class ImageSerializer(serializers.ModelSerializer):
 included_serializers = {
 "artist": "artist.serializers.ArtistSerializer"
 }
 class Meta:
 model = Image
 fields = ["artist"]

Defining the serializers as dotted import string should resolve your circular import problem.

Replies: 1 comment 1 reply

Comment options

Hi @Nekidev. This is a good question. Django REST framework JSON:API supports dotted import string to define included serializers.

This could look something likes this:

class ImageSerializer(serializers.ModelSerializer):
 included_serializers = {
 "artist": "artist.serializers.ArtistSerializer"
 }
 class Meta:
 model = Image
 fields = ["artist"]

Defining the serializers as dotted import string should resolve your circular import problem.

You must be logged in to vote
1 reply
Comment options

Thanks, I had tried using a string but without the serializers module since models do not require it.

Answer selected by Nekidev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /