简体   繁体   中英

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()

from OrderSerializer everything works fine and I get a lot of information about the Articles ie:

"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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM