我最近从PHP迁移到django。我正在创建一个在django上运行的项目..我习惯在php中编写自定义sql,因此我想使用raw()来过滤django中我的数据库中的结果。
然而,我无法完全理解django的工作原理..
请在下面找到我的代码。
目前我收到下面提到的输出
[('11677795635',), ('12345',)]
我想使用一些 for 循环并以下面提到的格式打印结果。
你可以帮我解决如何在django中循环播放..
在PHP中,
$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};
}
models.py
class customerinfo(models.Model):
customerbuyingid = models.CharField(max_length=300, default='invalid customer id in database')
customername = models.CharField(max_length=300, default='invalid customer name in database')
customerphonenumber = models.CharField(max_length=12, default='0000000000')
customermailid= models.CharField(max_length=80, default='email@email.com')
class orders(models.Model):
orderid = models.CharField(max_length=200)
orderstatus = models.CharField(max_length=10)
externalpurchaseid = models.CharField(max_length=100)
externalstatus = models.CharField(max_length=100)
customerid = models.CharField(max_length=100)
ops = models.CharField(max_length=100)
orderdate = models.DateField()
updatedon = models.DateTimeField(default=timezone.now)
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>
答案 0 :(得分:0)
只需替换:
在views.py中:
row = cursor.fetchall()
print (row)
context = {"row": row}
使用:
ids = []
for row in cursor.fetchall():
id = row[0]
ids.append(id)
context = {'rows': ids}
...
index.html中的:
{{ row }}
与
{% for id in rows %}
{{ id }}
{% endfor %}