Django rest framewor处理许多= True序列化器数据以列出

时间:2019-06-21 05:58:09

标签: django django-rest-framework

我得到这样的数据。

{
    "id": 1,
    "fields": [
        {"id": 1, "name": "att1"},
        {"id": 2, "name": "att2"}
    ]
}

我需要没有像fields: ["att1", "att2"]这样的键的字段。

我可以使用SerializerMethod来做到这一点。是否有类似source='form.fields.name'的方法?

CharField(source='form.fields.name')不能用于许多= True对象。

代码:


class EavForm(models.Model):
    name = models.CharField(max_length=300)

class EavAttribute(models.Model):
    form = models.ForeignKey(EavForm, on_delete=models.CASCADE, related_name='fields')
    name = models.CharField(max_length=300)

class EavAttributeSerializer(serializers.ModelSerializer):
    class Meta:
        model = EavAttribute
        fields = '__all__'


class EavFormSerializer(serializers.ModelSerializer):
    fields = EavAttributeSerializer(many=True)

    class Meta:
        model = EavForm
        fields = '__all__'

我有一个EavValue对象related_to EavForm。如何获得像eav_value_obj.fields这样的字段作为列表?

class EavValue(models.Model):
    form = models.ForeignKey(EavForm, on_delete=models.CASCADE, related_name='values')
    fields = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='form.fields.name' # not work like this. 
    )

1 个答案:

答案 0 :(得分:0)

您可以使用SlugRelatedField

class EavFormSerializer(serializers.ModelSerializer):
    fields = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='name'
    )

    class Meta:
        model = EavForm
        fields = '__all__'