【问题标题】:Error while executing query执行查询时出错
【发布时间】:2010-05-26 03:00:38
【问题描述】:

我收到有关此查询的错误消息

query = "select count(*) from pgns_game where raw_moves = %s"
params = ('a',)
total_rows = self.model.objects.raw(query, params)

它说

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

我显然错过了一些东西,但我不知道是什么。有什么想法吗?

【问题讨论】:

  • 在文档 (docs.djangoproject.com/en/1.2/topics/db/sql/…) 中说:“只有一个字段不能省略——主键字段。Django 使用主键来识别模型实例,因此它必须始终包含在原始查询中。如果您忘记包含主键,则会引发 InvalidQuery 异常。"

标签: django


【解决方案1】:

self.model.objects.raw() 期望查询结果包含来自模型 self.model 的主键,因此它可以将这些转换为函数结果的对象列表。

您真正需要做的是execute the SQL directly, and not through a manager. 您的代码可能如下所示:

from django.db import connection
cursor = connection.cursor()
cursor.execute("select count(*) from pgns_game where raw_moves = %s", ['a'])
total_rows = cursor.fetchone()

不过,我自己还没有尝试过。

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2012-11-04
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2014-08-27
    • 2015-07-18
    相关资源
    最近更新 更多