gpt4 book ai didi

python - Django:如何获取原始 SQL "COUNT(*)"查询的结果?

转载 作者:行者123 更新时间:2023-11-29 07:18:31 25 4
gpt4 key购买 nike

我有一个关键字表,如下所示:

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 中的 titlesummary 字段上有一个全文索引。

以下搜索工作正常:

select count(*) from blog_posts where match(title,summary) against ('paid'); 

现在我想用 blog_postskeyword 出现的行数填充字段 keywords.blog_posts_fulltext_count

当我运行这个时:

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 行时,它抛出:

raise InvalidQuery('Raw query must include the primary key')

我还尝试将查询字符串定义为:

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 here .

如果你想运行一个不会返回模型对象的查询,而是返回一些不同的东西(比如数字),你必须使用同一页面的另一部分中描述的方法 — Executing custom SQL directly .

一般的想法是您必须使用游标(在数据库结果集上迭代的东西)并获得唯一的结果。以下示例应该可以让您了解如何执行此操作。

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]

关于python - Django:如何获取原始 SQL "COUNT(*)"查询的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829175/

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