我试图在我的HTML视图中显示Django(2.0.5)的我的SQL聚合查询的结果,但我得到了这个错误信息:
'User' object has no attribute 'META'
但是,我可以在终端中看到我的查询结果,因为我将它打印在我的view.py
。所以与sqlite的连接正在工作。
在我看来,我写过这样的东西:
class MyClass(UserPassesTestMixin, DetailView):
def test_func(self, request):
cursor = connection.cursor()
cursor.execute('''select
a, count(b), c, d
from table1 inner join table2 ON table2.id = table1.b_id
where c < 2
group by a, d
order by d ''')
results = cursor.fetchone()
print(results)
context = {"results":results}
return render(request, "path/file.html", context)
在我的urls.py文件中,我有这样的东西:
path('/path/', MyClass.as_view(), name = 'my-class'),
并且在我的模板“file.html”中,当我点击一个按钮时,我试图访问我的结果:
<a href="{% url 'path:my-class' object.id %}" class="btn btn-primary" role="button">{% trans 'Show results' %}</a>
发布于 2018-06-11 13:36:44
class MyClass(UserPassesTestMixin, DetailView):
def test_func(self, request):
cursor = connection.cursor()
data = cursor.execute('''select
a, count(b), c, d
from table1 inner join table2 ON table2.id = table1.b_id
where c < 2
group by a, d
order by d ''')
results, = data.fetchone() # it returns a tuple and not a string as you might expect. since you have selected multiple columns
data = [row[0] for row in results.fetchall()]
translation_table = dict.fromkeys(map(ord, '+-(),'), None)
results = results.translate(translation_table)
print(results)
context = {"results":results}
cursor.close()
return render(request, "path/file.html", context)
发布于 2018-06-11 14:43:19
使用基于函数的视图而不是基于类的视图。
def my_view(request):
cursor = connection.cursor()
cursor.execute('''...''')
results = cursor.fetchone()
print(results)
context = {"results":results}
return render(request, "path/file.html", context)
并更改你的URL模式以使用
path('/path/', my_view, name = 'my-view'),
https://stackoverflow.com/questions/-100005291
复制相似问题