I have a SQL query in a Django view and store the results in a variable. As far I know the result should be stored as a list.
我在Django视图中有一个SQL查询,并将结果存储在一个变量中。据我所知,结果应该存储为列表。
def assignments(request):
cursor = connection.cursor()
cursor.execute("SELECT o.article_id, o.amount, m.id, o.create_date, m.status FROM orders o, producers p, machines ma, matches m WHERE ma.producer_id=1 AND m.machine_id = ma.id AND m.order_id = o.id")
articles = cursor.fetchall()
context = {"article_list": articles}
return render(request, 'assignments.html', context)
Then I want to transfer that data row by row in a table in my template.
然后我想在我的模板中的表中逐行传输该数据。
{% block body %}
<div class="container">
<table class="table">
<thead>...</thead>
<tbody>
{% for articles in article_list %}
<tr>
<td>{{ articles.article_id }}</td>
<td>{{ articles.amount }}</td>
<td>{{ articles.id}}</td>
<td>{{ articles.create_date }}</td>
<td>{{ articles.status }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Unfortunately the table is empty and is not showing any results. The query itself should be fine. I tested the query in my database workbench and it is showing the correct results.
不幸的是,该表是空的,没有显示任何结果。查询本身应该没问题。我在我的数据库工作台中测试了查询,它显示了正确的结果。
How can I access the data stored in variable articles
from my template?
如何从模板中访问存储在变量文章中的数据?
PS: I'm far from being a programmer. So I don't really know any programming concepts/language.
PS:我不是一个程序员。所以我真的不懂任何编程概念/语言。
Any help is highly appreciated. Thanks!
任何帮助都非常感谢。谢谢!
1 个解决方案
#1
1
You have a list of lists. Each element in articles_list
is just a list of values from the database; it does not have any knowledge of attributes like "id" or "amount".
你有一份清单清单。 articles_list中的每个元素只是数据库中的值列表;它不具备“id”或“amount”等属性的任何知识。
As Arpit says in the comments, you should be using Django models for this rather than raw SQL.
正如Arpit在评论中所说,你应该使用Django模型而不是原始SQL。
#1
1
You have a list of lists. Each element in articles_list
is just a list of values from the database; it does not have any knowledge of attributes like "id" or "amount".
你有一份清单清单。 articles_list中的每个元素只是数据库中的值列表;它不具备“id”或“amount”等属性的任何知识。
As Arpit says in the comments, you should be using Django models for this rather than raw SQL.
正如Arpit在评论中所说,你应该使用Django模型而不是原始SQL。