型号名称显示在Django temp中

2024-04-26 05:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的新手,所以我只是构建一些简单的应用程序来增加我的知识。我试图显示一个串联列表,但是当我显示列表时,它会显示模型名称,如下所示:

[<FamousQuote: Be yourself; everyone else is already taken>][<InfamousQuote: . I dunno. Either way. >]

这是my 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 %}

是我做错了什么,还是有更好的方法


Tags: 文件列表indexbyobjectsrequestorderall
1条回答
网友
1楼 · 发布于 2024-04-26 05:41:59

您有一个列表列表,因此该列表的unicode表示形式包含<ObjectName:string>,如果您有一个模型对象列表,您将获得对象的适当__unicode__表示形式

最终,模板将自动尝试将python对象转换为它的字符串表示形式,在QuerySet的情况下是[<object: instance.__unicode__()>]

您已经清楚地为对象实例定义了所需的字符串表示形式—您只需要确保模板引擎接收这些实例—而不是其他类

看看shell中输出的差异

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 %}

热释光;博士

您有列表的列表,所以您加入的是列表的字符串表示,而不是实例

相关问题 更多 >