Django无法转换Recipe_instruction'隐含地反对str

时间:2016-09-15 20:27:26

标签: python django

我正在开发django中的应用程序。这是我的models.py和views.py代码:

#models.py
class Recipe_instruction(models.Model):
    content = models.TextField(max_length=500)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    order = models.IntegerField(max_length=500)
    class Meta:
            app_label='recipe_base'
    def __str__(self):
        return self.content

views.py

#create recipes_dict
...
        recipe_instructions = Recipe_instruction.objects.filter(recipe = recipe)
        recipe_instructions_string = ""
        for recipe_instruction in recipe_instructions:
            recipe_instructions_string = recipe_instructions_string + recipe_instruction.content


...

我的目标是获取所有食谱说明并将它们组合成一个字符串recipe_instructions_string

但是当我运行views.py时,它会给我以下错误:

recipe_instructions_string = recipe_instructions_string + recipe_instruction.content
TypeError: Can't convert 'Recipe_instruction' object to str implicitly

谁能告诉我发生了什么?

由于recipe_instruction.content是一个文本字段,因此我不需要再将其转换为字符串,因为它已经是一个字符串。

TRACEBACK:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/root/worker/worker/views.py", line 500, in Task1
    recipe_instructions_string = recipe_instructions_string + recipe_instruction.content
TypeError: Can't convert 'Recipe_instruction' object to str implicitly

1 个答案:

答案 0 :(得分:1)

问题不在于此处的代码..但在我们查看它时,请尝试将整个代码更改为

instructions = Recipe_instruction.objects.filter(recipe=recipe).values_list('content',
                                                                            flat=True)
recipe_instructions_string  = "".join(instructions)

这样可以阻止错误发生,如果它在这里,并且效率更高。