Django serializer classes referencing each other

2019-05-20 04:03发布

问题:

I need to have two serializer classes referencing each other but I'm getting one of the classes not defined if both classes are referencing each other. I created a duplicate of one of the class w/ a difference name and this seems to work but is there a better way to do this without making 3 classes?

class ArtistSerializer(serializers.ModelSerializer):

    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name',)

class TrackSerializer(serializers.ModelSerializer):

    artist = ArtistSerializer(read_only=True)
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)

class ArtistSerializer2(serializers.ModelSerializer):

    name = serializers.CharField()
    tracks = TrackSerializer(many=True, read_only=True)
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')

回答1:

This is a circular class dependency. Your solution is one of the work arounds available for it. Another option is to avoid the circular dependecy all together by using a StringRelatedField

StringRelatedField may be used to represent the target of the relationship using its unicode method.

class ArtistSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)
    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')

class TrackSerializer(serializers.ModelSerializer):

    artist = StringRelatedField()  # read only by default.
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)