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__'
答案 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()