gpt4 book ai didi

python - Django View 中的原始 SQL 查询

转载 作者:行者123 更新时间:2023-11-28 19:36:57 24 4
gpt4 key购买 nike

如何在 views.py 中使用原始 SQL 执行以下操作?

from app.models import Picture

def results(request):
all = Picture.objects.all()
yes = Picture.objects.filter(vote='yes').count()
return render_to_response(
'results.html',
{'picture':picture, 'all':all, 'yes': yes},
context_instance=RequestContext(request)
)

这个 results 函数会是什么样子?

最佳答案

>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute('''SELECT count(*) FROM people_person''')
1L
>>> row = cursor.fetchone()
>>> print row
(12L,)
>>> Person.objects.all().count()
12

使用 WHERE 子句过滤赞成票:

>>> cursor.execute('''SELECT count(*) FROM people_person WHERE vote = "yes"''')
1L

关于python - Django View 中的原始 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com