0

我正在尝试使用.extra()查询返回超过 1 个结果的位置,例如:

'SELECT "books_books"."*" FROM "books_books" WHERE "books_books"."owner_id" = %s' % request.user.id

我收到一个错误:only a single result allowed for a SELECT that is part of an expression

使用 sqlite3 在开发服务器上尝试。有人知道如何解决这个问题吗?还是我的查询有误?

编辑:

我正在使用django-simple-ratings,我的模型是这样的:

class Thread(models.Model):
    #
    #
    ratings = Ratings()

我想显示每个Thread的评分以及用户是否已经评分。对于 2 个项目,它将命中 6 次,实际命中 1 次,Thread访问 2次ratings。查询:

    threads = Thread.ratings.order_by_rating().filter(section = section)\
                .select_related('creator')\
                .prefetch_related('replies')

    threads = threads.extra(select = dict(myratings = "SELECT SUM('section_threadrating'.'score') AS 'agg' FROM 'section_threadrating' WHERE 'section_threadrating'.'content_object_id' = 'section_thread'.'id' ",)

然后我可以打印每个Thread人的评分,而不需要更多地访问数据库。对于第二个查询,我添加:

   #continue from extra 
   blahblah.extra(select = dict(myratings = '#####code above####',
                                voter_id = "SELECT 'section_threadrating'.'user_id' FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))

硬编码user_id. 然后当我在这样的模板上使用它时:

{% ifequal threads.voter_id user.id %}
#the rest of the code

我收到一个错误:only a single result allowed for a SELECT that is part of an expression

如果还不够清楚,请告诉我。

4

1 回答 1

1

问题出在查询中。通常,当您编写子查询时,它们必须只返回 1 个结果。所以一个像这样的子查询voter_id

select ..., (select sectio_threadrating.user_id from ...) as voter_id from ....

无效,因为它可以返回多个结果。如果你确定它总是返回一个结果,你可以使用max()ormin()聚合函数:

blahblah.extra(select = dict(myratings = '#####code above####',
                             voter_id = "SELECT max('section_threadrating'.'user_id') FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))

这将使子查询始终返回 1 个结果。

删除该硬代码,您希望在此处检索什么 user_id?也许您不能仅使用 SQL 减少到 1 个用户。

于 2012-12-19T10:55:38.120 回答