Django序列化器类相互引用 [英] Django serializer classes referencing each other
问题描述
我需要有两个互相引用的序列化器类,但是如果两个类都相互引用,我将得到一个未定义的类。我创建了一个带有差异名称的类的副本,这似乎可行,但是有没有更好的方法而又不进行3个类的实现呢?
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')
推荐答案
此是循环类依赖项。您的解决方案是可用的解决方法之一。另一种选择是通过使用 StringRelatedField <来避免所有循环依赖。 / a>
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可以使用其 unicode 来表示
关系的目标。
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',)
这篇关于Django序列化器类相互引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!