问题描述
我是Django的新手,所以我只是构建一些简单的应用程序来增加我的知识。 我试图显示一个串联列表,但是当我显示列表时,它会显示模型名称,如下所示:
[<FamousQuote: Be yourself; everyone else is already taken>][<InfamousQuote: . I dunno. Either way. >]
这是我的views.py文件:
def index(request):
famous_quote = FamousQuote.objects.all().order_by('?')[:1]
infamous_quote = InfamousQuote.objects.all().order_by('?')[:1]
compiled = [famous_quote, infamous_quote]
return render(request, 'funnyquotes/index.html', {'compiled': compiled})
和我的index.html文件:
{% if compiled %}
{{ compiled|join:"" }}
{% else %}
<p>No quotes for you.</p>
{% endif %}
我做错了什么,还是可以做的更好的方法?
1楼
您有一个列表列表,因此列表的unicode表示形式包含<ObjectName:string>
,如果您有一个模型对象列表,则可以得到正确的__unicode__
对象表示形式。
最终,模板将自动尝试将python对象转换为其字符串表示形式,在QuerySet
的情况下为[<object: instance.__unicode__()>]
。
您已经清楚地为对象实例定义了所需的字符串表示形式-您只需要确保模板引擎接收到这些实例即可-而无需其他类。
查看外壳程序中输出的差异。
print(FamousQuote.objects.all().order_by('?')[:1]) # calls str(QuerySet)
# vs
print(FamousQuote.objects.order_by('?')[0]) # calls str(FamousQuote)
要么更新您的视图
compiled = [famous_quote[0], infamous_quote[0]]
或您的模板
{% for quotes in compiled %}{{ quotes|join:"" }}{% endfor %}
TL; DR
您具有列表列表,因此要加入列表的字符串表示形式,而不是实例的字符串表示形式。