[英]Django: How to Get the Result of a Raw SQL "COUNT(*)" Query?
我有一个关键字表,如下所示:
CREATE TABLE `keywords` (
`keyword` VarChar( 48 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`id` Int( 11 ) AUTO_INCREMENT NOT NULL,
`blog_posts_fulltext_count` Int( 11 ) NOT NULL,
PRIMARY KEY ( `id` ) )
我还有一个博客文章表,如下所示:
CREATE TABLE `blog_posts` (
`id` Int( 11 ) AUTO_INCREMENT NOT NULL,
`title` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL,
`summary` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL,
PRIMARY KEY ( `id` ) );
CREATE FULLTEXT INDEX `title_summary_fulltext` ON `blog_posts`( `title`, `summary` );
如您所见,我在blog_posts
title
和summary
字段上有一个全文索引。
以下搜索工作正常:
select count(*) from blog_posts where match(title,summary) against ('paid');
现在我想用keyword
出现在blog_posts
中的行数填充keywords.blog_posts_fulltext_count
blog_posts
字段。
当我运行这个时:
keywords = Keywords.objects.all()
for the_keyword in keywords:
query = "select count(id) from BlogPosts where match(title,summary) against ('{0}')".format(the_keyword.keyword)
number_of_mentions = blog_posts.objects.raw(query)
for obj in number_of_mentions:
a = obj
... RawQuerySet number_of_mentions
似乎没有错误返回,并且number_of_mentions.query
包含:
'select count(id) from blog_posts where match(title,summary) against ('paid')'
但是当代码for obj in number_of_mentions
行中运行for obj in number_of_mentions
,它会抛出:
raise InvalidQuery('原始查询必须包含主键')
我还尝试将查询字符串定义为:
query = "select count('id') from BlogPosts where match(title,summary) against ('{0}')".format(the_keyword.keyword)
...并作为:
query = "select count(*) from BlogPosts where match(title,summary) against ('{0}')".format(the_keyword.keyword)
...产生相同的错误消息。
从 Django 中的原始 sql COUNT
命令获取结果的正确方法是什么?
当您使用blog_posts.objects.raw()
,Django 期望原始查询以某种方式返回blog_posts
对象。 但是您的计数查询将返回单个数字而不是对象集合。 这就是您在此处看到的 API。
如果您想运行的查询不会返回模型对象,而是返回不同的对象(如数字),则必须使用同一页面另一部分中描述的方法 — 直接执行自定义 SQL 。
一般的想法是您必须使用游标(遍历数据库结果集的东西)并获得它的唯一结果。 下面的例子应该让你知道如何做到这一点。
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("select count(id) from BlogPosts where match(title,summary) against (%s)", [the_keyword.keyword])
# get a single line from the result
row = cursor.fetchone()
# get the value in the first column of the result (the only column)
count_value = row[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.