Django Rest Framework不显示StreamField中的内容 [英] Django Rest Framework does not show content from StreamField

查看:95
本文介绍了Django Rest Framework不显示StreamField中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StreamField中有一个带有ModelChooserBlock的模型类,如果我打开Django Rest Framework,我不会得到令人满意的结果。具体来说,成分应具有指向成分或直接指向数据库的链接。

I have a model class with ModelChooserBlock inside StreamField and If I open my Django Rest Framework I don't get a satisfactory result. Specifically "Ingredient" should have a link to ingredients or directly Database.

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "meta": {
        "type": "cultinadb.Menu",
        "detail_url": "http://127.0.0.1:8000/api/v2/menu/1/"
    },
    "title": "",
    "Ingredient": [
        {
            "type": "zutaten",
            "value": 2,
            "id": "647d762f-ec26-4c78-928a-446344b1cb8a"
        },
        {
            "type": "zutaten",
            "value": 1,
            "id": "6ab4e425-5e75-4ec0-ba63-8e7899af95e2"
        }
    ],
}

这是我的模型:

from django.db import models
from wagtail.api import APIField
from wagtailmodelchooser import register_model_chooser
from wagtailmodelchooser.blocks import ModelChooserBlock

@register_model_chooser
class Ingredient(models.Model):
    name = models.CharField(max_length=255)
    picture_url = models.URLField(blank=True)
    translate_url = models.URLField(blank=True)

    def __str__(self):
        return self.name

@register_model_chooser
class Menu(models.Model):
    Ingredient = StreamField([
        ('zutaten', ModelChooserBlock('kitchen.Ingredient')) ],
        null=True, verbose_name='', blank=True)

    panels = [
        MultiFieldPanel(
            [ StreamFieldPanel('Ingredient') ],
            heading="Zutaten", classname="col5"
        ),
    ]

    def __str__(self):
        return self.title

    api_fields = [
        APIField('Ingredient'),
    ]

我尝试使用序列化器按如下所示添加它,但随后出现错误。
我创建了serializer.py并添加了这段代码

I tried to add it as shown here with serializer, but then I got errors. I created serializer.py and added this code

class MenuRenditionField(Field):
    def get_attribute(self, instance):
        return instance
    def to_representation(self, menu):
        return OrderedDict([
            ('title', menu.Ingredient.name),
            ('imageurl', menu.Ingredient.picture_url),
            ('imageurl', menu.Ingredient.translate_url),
        ])

然后我像这样更改了api_fields

Then i changed my api_fields like this

api_fields = [
   APIField('Ingredient', serializer=MenuRenditionField()),
]

The添加此代码时出现的错误。

The error that I get when adding this code.

AttributeError at /api/v2/menu/1/
'StreamValue' object has no attribute 'name'
   Request Method:  GET
   Request URL: http://127.0.0.1:8000/api/v2/menu/1/
   Django Version:  1.11.1
   Exception Type:  AttributeError
   Exception Value: 
   'StreamValue' object has no attribute 'name'

我将非常感谢您的帮助。谢谢!

I will be very grateful for the help. Thanks!

推荐答案

您可以通过覆盖 get_api_representation 方法。在这种情况下,它可能类似于:

You can customise the API output of a StreamField block by overriding the get_api_representation method. In this case, it might look something like:

class IngredientChooserBlock(ModelChooserBlock):
    def get_api_representation(self, value, context=None):
        if value:
            return {
                'id': value.id,
                'name': value.name,
                # any other relevant fields of your model...
            }

然后使用在您的StreamField定义中,代替 ModelChooserBlock('kitchen.Ingredient')的I​​ngredientChooserBlock('kitchen.Ingredient')

Then use IngredientChooserBlock('kitchen.Ingredient') in place of ModelChooserBlock('kitchen.Ingredient') in your StreamField definition.

这篇关于Django Rest Framework不显示StreamField中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆