[英]Serialize custom field from an object in a list using the Django Rest Framework
I have a model that looks something like this: 我有一个看起来像这样的模型:
class Foo:
name = CharField()
class Bar:
foo = ForeignKey(Foo, related_name='bars')
bar_text = TextField()
I want the serialized version of Foo to look something like: 我希望Foo的序列化版本看起来像:
{
bars : [
"baz",
"whizz"
]
}
ie rather than displaying the id
s of each bar, displaying the 'bar_text' field inside instead. 即,不显示每个栏的id
,而是在其中显示“ bar_text”字段。
I think I'm aware of how to do this normally, ie if we had a single bar
attribute under each 'Foo' rather than a list: 我想我知道如何正常执行此操作,即,如果我们在每个“ Foo”下都有一个bar
属性,而不是一个列表:
class FooSerializer(models.ModelSerializer):
bar = serializers.TextField(source='bar.bar_text')
But I'm not sure how to perform the same override when using a 'bars' list, and don't seem to be able to find anything obvious! 但是我不确定使用“ bars”列表时如何执行相同的覆盖,而且似乎找不到任何明显的东西!
EDIT: I forgot to mention - I think I can do this by overriding the restore_object
function, but if there's a neater way, I'm all ears. 编辑:我忘了提-我想我可以通过重写restore_object
函数来做到这一点,但是如果有一种更整洁的方法,我将不胜枚举。
A solution that nearly works for me is to override the bars
attribute on the FooSerializer
with a BarSerializer
: 几乎适用于我一个解决方案是重写bars
上属性FooSerializer
用BarSerializer
:
class FooSerializer(models.ModelSerializer):
bars = BarSerializer(many=True)
However, this gives me the following when serialized: 但是,这给我以下序列化的信息:
{
bars: [
{
'bar_text' : 'baz',
},
{
'bar_text' : 'whizz'
}
]
}
Which is fine, but I really want a list of bar_text
s rather than key/value pairs. 很好,但是我真的想要bar_text
的列表,而不是键/值对。 What's more, if I add more fields to Bar
that I do not want to be serialized into Foo
, I have no control over which are displayed here vs. a pure serialization of Bar
. 此外,如果我向Bar
添加更多不想序列化为Foo
字段,那么与纯Bar
序列化相比,我无法控制此处显示的字段。 If I don't get a better solution I'll accept this shortly. 如果没有更好的解决方案,我会尽快接受。
It sounds like you are looking for a SlugRelatedField
instead of a nested serializer. 听起来您正在寻找SlugRelatedField
而不是嵌套的序列化器。
class FooSerializer(models.ModelSerializer):
bars = serializers.SlugRelatedField(slug_field='bar_text')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.