[英]Django Rest Framework: ModelSerializer as field in a ModelSerializer doesn't show choices
I have two Models: 我有两个模型:
class Article(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=8, decimal_places=2)
class Order(models.Model):
article = models.ForeignKey(article, related_name='orders')
bought_on = models.DateTimeField()
and two serializer classes: 和两个序列化器类:
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
class OrderSerializer(serializers.ModelSerializer):
article = ArticleSerializer()
class Meta:
model = Order
now if I want to request the OPTIONS of orders I don't get the "choices" and it looks like this: 现在,如果我想请求订单的选项,我没有得到“选择”,它看起来像这样:
"article": {
"type": "field",
"required": true,
"read_only": false,
"label": "Article"
},
If I delete 如果我删除
article = ArticleSerializer()
文章= ArticleSerializer()
from OrderSerializer everything works fine and I get a lot of information about the Articles ie: 从OrderSerializer一切正常,我获得了很多有关文章的信息,即:
"article": {
"type": "field",
"required": true,
"read_only": false,
"label": "Article",
"choices": [
{
"display_name": "Headphones - 29.00",
"value": "8"
},
{
"display_name": "Monitor- 199.00",
"value": "12"
},
]
},
So here is my Question: 所以这是我的问题:
Is there a possibility to overwrite the choices field in the ArticleSerializer or is there another way to display the Articles in the API View as choices 是否有可能覆盖ArticleSerializer中的choices字段,或者是否有另一种方式可以将API View中的Articles显示为options
Here is the answer Tom Christie has given me: 这是汤姆·克里斯蒂给我的答案:
You don't want to display it as choices if it's a nested item.
如果它是嵌套项目,则不想将其显示为选项。 Rather we should be displaying it as a nested field.
相反,我们应该将其显示为嵌套字段。 (We could consider that as a valid issue, tho I'd see it as pretty low priority on my own radar, so unless someone else was running with it, then...)
(我们可以认为这是一个有效的问题,在我自己的雷达上,我认为它的优先级很低,因此,除非其他人正在运行它,否则...)
In terms of supporting this in your own project (rather than in core), there's some limited info on how you can go about this here... http://www.django-rest-framework.org/api-guide/metadata/ but you'd also want to dig into the existing metadata class implementation.
关于在您自己的项目中(而不是在核心中)支持这一点,这里有一些有限的信息说明了如何进行此操作... http://www.django-rest-framework.org/api-guide/metadata /,但您也想深入研究现有的元数据类实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.