python django在html中自定义查询结果
刚开始学习python django框架,我试图在html页面中显示一个自定义查询结果。python django在html中自定义查询结果
def index(request):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM polls_post")
context ={
'all_posts':cursor.fetchall()
}
在我的HTML页面
<ul>
{% for post in all_posts %}
<li>{{ post }}</li>
{% endfor %}
</ul>
但它显示的值的元组,所以我怎样才能查询与表的列名的结果,例如我可以打印像这样的价值观
<ul>
{% for post in all_posts %}
<li>{{ post.title }}</li>
<li>{{ post.name }}</li>
{% endfor %}
</ul>
不能 - 使用光标,你需要自己内部视图重新包装的数据和然后将对象列表传递给模板。
喜欢的东西
posts = []
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM polls_post")
for obj in cursor.fetchall():
posts.append({"title": obj[0], "name": obj[1]})
context = {'all_posts':cursor.fetchall()}
不过我想你更愿意使用Django的ORM框架。那么看看Model reference。
是否有任何简单的操作呢?无需手动使用列名 –
@BlessanKurien,查看文档参考 - https://docs.djangoproject.com/el/1.10/topics/db/sql/ 有一个使用'cursor.description' – maxwell
为什么你在你的视图中使用sql查询。尝试使用Django ORM and QuerySets。
可能这是帮助你
Django的查看
def your_view(request):
all_posts = your_model_class_name.objects.all()
return render_to_response("your_html.html", {'all_posts': all_posts})
而且在你的HTML页面
<ul>
{% for post in all_posts %}
<li>{{ post.title }}</li>
<li>{{ post.name }}</li>
{% endfor %}
</ul>
我会得到'polls_post'中的未解决的参考错误 –
杆柱是你的类名请替换它。 –
所以我需要使用ORM层,但我不需要它 –
你也可以这样做
def your_view(request):
all_posts = model_class_name.objects.raw("Select * from tablename");
return render_to_response("your_html.html", {'all_posts': all_posts})
,并在模板
<ul>
{% for post in all_posts %}
<li>{{ post.title }}</li>
<li>{{ post.name }}</li>
{% endfor %}
</ul>
原始查询是有帮助的,当我们使用复杂的查询
如果你刚开始学习Django的,你发什么认为最好的方法是运行原始SQL查询而不是使用记录良好的模型层? –
我需要知道这是可能的,这就是所有:) –