从ManyToManyField DRF序列化一个字段

时间:2016-04-27 04:07:41

标签: python django django-rest-framework

我有很多帖子,DRF文档(需要很多爱),我还没有找到如何做到这一点,没有一个复杂的混乱。

我需要这个输出:

[{"id":1,"name":"memcheck","subscribers":["foo", "bar"]}]

如果我采用DRF方式(或至少文档如何指示我如何操作),那么我得到这个输出:

[{"id":1,"name":"memcheck","subscribers":["Subscriber object", "Subscriber object"]}]

我尝试取消注释并使用第二个选项,然后我得到了这个输出:

[{"id":1,"name":"memcheck","subscribers":[{"name": "foo"}, {"name": "bar"}]}]

models.py

class Subscriber(models.Model):
    name = models.CharField(max_length=100)


class Check(models.Model):
   name = models.CharField(max_length=100)
   description = models.TextField(null=True, blank=True)
   subscribers = models.ManyToManyField(Subscriber)

serializers.py

class SubscriberSerializer(serializers.ModelSerializer):
    name = serializers.CharField()

    class Meta:
        fields = ('name', )


class CheckSerializer(serializers.ModelSerializer):
    # using source=('name') or variants like: 'subscribers__name', 'subscribers.name' 
    # doesnt work
    subscribers = serializers.ListSerializer(child=serializers.CharField())
    # subscribers = SubscriberSerializer(many=True) # --> see 2nd output

    class Meta:
        model = Check
        fields = ('id', 'name', 'subscribers')

在ManyToMany的其他情况下,我想获得dict列表,但在这种情况下,我只想要一个名为attr的简单列表..为什么这么难做呢?

1 个答案:

答案 0 :(得分:3)

您只需要一个SlugRelatedField

class CheckSerializer(serializers.ModelSerializer):

    subscribers = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')

    class Meta:
        model = Check
        fields = ('id', 'name', 'subscribers')