Django序列化程序类相互引用

时间:2017-06-04 05:51:51

标签: python django django-rest-framework

我需要让两个序列化程序类相互引用,但如果两个类都相互引用,我会得到一个未定义的类。我创建了一个带有差异名称的类之一的副本,这似乎有效,但有没有更好的方法来做到这一点而不需要3个类?

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 个答案:

答案 0 :(得分:3)

这是循环类依赖项。您的解决方案是可用的解决方案之一。另一个选择是使用StringRelatedField

来避免循环依赖
  

StringRelatedField可用于表示目标   关系使用 unicode 方法。

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',)