Django Rest Framework不显示StreamField的内容

时间:2017-08-23 15:02:48

标签: django wagtail django-rest-framework

我在StreamField中有一个ModelChooserBlock的模型类,如果我打开我的Django Rest Framework,我就不会得到满意的结果。特别是"成分"应该有成分链接或直接数据库。

rem ORIENTDB MAXIMUM HEAP. USE SYNTAX -Xmx<memory>, WHERE <memory> HAS THE TOTAL MEMORY AND SIZE UNIT. EXAMPLE: -Xmx512m
set MAXHEAP=-Xmx6G 
rem ORIENTDB MAXIMUM DISKCACHE IN MB, EXAMPLE: "-Dstorage.diskCache.bufferSize=8192" FOR 8GB of DISKCACHE
set MAXDISKCACHE=8GB 

这是我的模特:

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"
        }
    ],
}

I tried to add it as shown here使用序列化程序,但后来我遇到了错误。 我创建了serializer.py并添加了这段代码

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'),
    ]

然后我像这样改变了我的api_fields

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 = [
   APIField('Ingredient', serializer=MenuRenditionField()),
]

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

1 个答案:

答案 0 :(得分:3)

您可以通过覆盖get_api_representation方法来自定义StreamField块的API输出。在这种情况下,它可能看起来像:

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定义中使用IngredientChooserBlock('kitchen.Ingredient')代替ModelChooserBlock('kitchen.Ingredient')