从ManyToManyField DRF序列化一个字段 [英] Serializing one field from a ManyToManyField DRF
本文介绍了从ManyToManyField DRF序列化一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多帖子,DRF文档(需要很多的爱),而且我还找不到没有复杂混乱的方法.
I have been lot of posts, the DRF documentation (which needs LOT of love), and I couldn't find yet how to do this without a complicated mess.
我需要以下输出:
[{"id":1,"name":"memcheck","subscribers":["foo", "bar"]}]
如果我采用DRF方式(或者至少是文档指出我的方式),那么我会得到以下输出:
If I go with the DRF way (or at least how the docs point me how to do it), then I get this output:
[{"id":1,"name":"memcheck","subscribers":["Subscriber object", "Subscriber object"]}]
我尝试取消注释并使用第二个选项,然后得到以下输出:
I tried uncommenting and going with a second option, then I get this output:
[{"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的其他情况下,我希望有字典列表,但是在这种情况下,我只想要一个简单的列表,其名称为attr ..为什么这样做太难了?
In other cases of ManyToMany I would like to have the list of dict, but in this case I just want a simple list with the name attr.. why is too hard to do it?
推荐答案
您只需要 SlugRelatedField
:
class CheckSerializer(serializers.ModelSerializer):
subscribers = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')
class Meta:
model = Check
fields = ('id', 'name', 'subscribers')
这篇关于从ManyToManyField DRF序列化一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文