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
}多谢你们的支持!
发布于 2017-08-29 09:28:09
这里的问题是,您要从{'ingredients': value.ingredient}返回WeekChooserBlock.get_api_representation。这里value.ingredient是一个StreamValue实例,它是一个复杂的特定于Wagtail的对象,包含模板呈现的方法,以及实际的流数据- DRF不知道如何处理这个复杂的对象。
您需要确保您的get_api_representation响应仅由标准的Python组成,例如字符串和dicts。例如:
class WeekChooserBlock(ModelChooserBlock):
def get_api_representation(self, value, context=None):
if value:
return {
'ingredients': [ingredient.value['name'] for ingredient in value.ingredient],
}如果您希望重用您在IngredientChooserBlock.get_api_representation中定义的成分的API表示,它会遇到一些小技巧,但是您应该能够使用以下方法来实现:
class WeekChooserBlock(ModelChooserBlock):
def get_api_representation(self, value, context=None):
if value:
ingredient = value.ingredient
return ingredient.stream_block.get_api_representation(ingredient, context=context)https://stackoverflow.com/questions/45934876
复制相似问题