Django-Rest-Framework中的Serializer问题

时间:2015-03-13 07:38:47

标签: python django django-rest-framework

我想为我的模型创建具有嵌套关系的序列化器。我的模型如下所示:

class Master(models.Model):
    en = models.TextField('English')

class Album(models.Model):
    pk_album = models.AutoField(primary_key=True, serialize=True)
    title = models.OneToOneField(Master, related_name='Album_title')
    description = models.OneToOneField(Master, related_name='Album_description')


class Track(models.Model):
    pk_track = models.AutoField(primary_key=True)
    fk_album_parent = models.ForeignKey('Album', related_name='track_parent')
    fk_album_child = models.ForeignKey('Album', related_name='track_child')

和我的序列化程序:

class masterSerializer(serializers.ModelSerializer):
    class Meta:
        model = Master
        fields = ('en',)

class albumSerializer(serializers.ModelSerializer):
    album_title = masterSerializer()
    album_description = masterSerializer()

    class Meta:
        model = Album
        fields = ('album_title', 'album_description')

class trackSerializer(serializers.ModelSerializer):
    track_parent = albumSerializer(many=True, read_only=True)
    track_child = albumSerializer(many=True, read_only=True)

    class Meta:
        model = Track
        fields = ('track_parent', 'track_child')

我在观点中使用此trackSerializer。但是在浏览器中我什么都没有意味着没有字段或数据只是空白的json。

我很困惑如何在serlaizer中处理这种嵌套关系,以便我的最终API工作正常。

1 个答案:

答案 0 :(得分:1)

您以错误的方式定义了trackSerializer

Track模型没有track_parenttrack_child属性。它们属于Album模型。请记住,related_name是一个属性,用于定义指向模型(在本例中为Album)如何检索其向后模型实例(即Track实例)的方式。 related_name不会像您认为的那样重命名该属性。

此外,track_parent代表Track个实例,您无法使用Track序列化albumSerializer个实例

class trackSerializer(serializers.ModelSerializer):

    class Meta:
        model = Track
        fields = ('pk_track',)


class albumSerializer(serializers.ModelSerializer):
    album_title = masterSerializer()
    album_description = masterSerializer()
    track_parent = trackSerializer(many=True, read_only=True)
    track_child = trackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ('album_title', 'album_description','track_parent', 'track_child')