如何在Django-rest-framework中复制相关字段

时间:2019-07-03 13:34:27

标签: django django-rest-framework

fields是诸如['a', 'b', 'c']之类的EavAttribute名称的列表

fields_order是类似于[1,2,3]的EavAttribute顺序的列表,foreign keys与字段相同。

我想将字段的副本复制到serializer的订单字段列表中。

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)
    order = models.IntegerField(default=1)

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

    # not work here ,how to fix 
    fields_order = serializers.SlugRelatedField(many=True,read_only=True,slug_field='order')

    class Meta:
        model = EavForm
        fields = '__all__'

1 个答案:

答案 0 :(得分:0)

您可以使用Serializermethodfield

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


    fields_order = serializers.SerializerMethodField()

    def get_field_order(self, obj):
        return obj.fields.all()