我正在 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 (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
最佳答案
问题不在于这里的代码..但是当我们查看它时,尝试将整个代码更改为
instructions = Recipe_instruction.objects.filter(recipe=recipe).values_list('content',
flat=True)
recipe_instructions_string = "".join(instructions)
如果错误在这里,这将阻止错误发生,并且效率更高。
关于python - Django 无法将 'Recipe_instruction' 对象隐式转换为 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39519796/