【发布时间】:2018-02-06 15:51:15
【问题描述】:
Previous topic where I was kindly helped by @gasman 所以我有一个模型类成分,例如:
@register_model_chooser
class Ingredient(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
为了在 API 中表示这一点,我创建了这个类:
class IngredientChooserBlock(ModelChooserBlock):
def get_api_representation(self, value, context=None):
if value:
return {
'name': value.name,
}
然后我有另一个使用IngredientChooserBlock 类的模型类:
@register_model_chooser
class Menu(models.Model):
ingredient = StreamField([
('zutaten', IngredientChooserBlock('kitchen.Ingredient')) ],
null=True, verbose_name='', blank=True)
def __str__(self):
return self.title
因为我在我的 API 中需要这个 ingredient,所以我创建了相同的模型类来覆盖 get_api_representation:
class WeekChooserBlock(ModelChooserBlock):
def get_api_representation(self, value, context=None):
if value:
return {
'ingredients': value.ingredient,
}
最后在我的主模型类中,我尝试使用这个WeekChooserBlock,它以kitchen.Menu 作为参数,如下所示:
class Week(models.Model):
dishes_sp = StreamField([
('menu', WeekChooserBlock('kitchen.Menu')) ],
null=True, verbose_name='', blank=True)
问题是它在 DRF 中打印出如下错误:
Object of type 'StreamValue' is not JSON serializable
不想提出太大的问题,但为了更清楚起见,我的 Menu 类中实际上还有另一个对象,例如:
class Menu(models.Model):
title = models.CharField(max_length=255)
image = models.URLField(blank=True, null=True)
price = models.FloatField(blank=True, null=True, max_length=255)
ingredient = StreamField([
('zutaten', IngredientChooserBlock('kitchen.Ingredient')) ],
null=True, verbose_name='', blank=True)
steps = StreamField([
('Schritt', TextBlock())
], null=True, verbose_name='Vorbereitungsschritte', blank=True)
我也试图代表他们。但是只有当我尝试输出StreamField时才会显示错误
class WeekChooserBlock(ModelChooserBlock):
def get_api_representation(self, value, context=None):
if value:
return {
'title': value.title,
'picture': value.image,
'price': value.price,
'ingredients': value.ingredient,
'steps': value.steps
}
感谢您的支持!
【问题讨论】:
标签: django wagtail django-rest-framework wagtail-streamfield