Php 在Django中使用原始SQL
我最近从PHP迁移到django。我正在创建一个在django上工作的项目。。我习惯于用php编写自定义sql,因此我想使用raw()从django数据库中筛选结果 然而,我不能完全理解django是如何工作的 请在下面找到我的代码 目前,我正在收到下面提到的输出Php 在Django中使用原始SQL,php,python,django,django-views,django-database,Php,Python,Django,Django Views,Django Database,我最近从PHP迁移到django。我正在创建一个在django上工作的项目。。我习惯于用php编写自定义sql,因此我想使用raw()从django数据库中筛选结果 然而,我不能完全理解django是如何工作的 请在下面找到我的代码 目前,我正在收到下面提到的输出 [('11677795635',), ('12345',)] 我想使用一些进行循环,并以下面提到的格式打印结果 1167795635 12345 你能帮助我如何在django进行for循环吗 在PHP中, 同样的情况也有可能发生
[('11677795635',), ('12345',)]
我想使用一些进行循环,并以下面提到的格式打印结果
同样的情况也有可能发生
$query=mysql_query("SELECT abcdashboard_customerinfo.customerbuyingid FROM abcdashboard_customerinfo WHERE abcdashboard_customerinfo.customerbuyingid in (select DISTINCT abcdashboard_orders.customerid from abcdashboard_orders)");
$queryrun=mysql_num_rows($query);
for ($f=0; $f <$queryrun; $f++)
{
${'customer'.$f}=mysql_result($query,$f, 'customerbuyingid');
echo ${'customer'.$f};
}
views.py
def index(request):
all_customer = customerinfo.objects.all()
cursor = connection.cursor()
cursor.execute('''SELECT abcdashboard_customerinfo.customerbuyingid FROM abcdashboard_customerinfo WHERE abcdashboard_customerinfo.customerbuyingid in (select DISTINCT abcdashboard_orders.customerid from abcdashboard_orders) ''')
row = cursor.fetchall()
print (row)
context = {"row": row}
return render(request, "abcdashboard/index.html", context)
Index.html
<html>
<head>
<title>
</title>
</head>
<body>
<ul>
<h2 align="center"> SQL Queries display </align> </h2>
{% block content %}
{{ row }}
{% endblock %}
</ul>
</body>
</html>
SQL查询显示
{%block content%}
{{row}}
{%endblock%}
只需更换:
在views.py中:
row = cursor.fetchall()
print (row)
context = {"row": row}
与:
在index.html中:
{{ row }}
与
不要这样做。如果你想写Django,你应该写Django
ids = []
for row in cursor.fetchall():
id = row[0]
ids.append(id)
context = {'rows': ids}
...
{{ row }}
{% for id in rows %}
{{ id }}
{% endfor %}