django使用.extra()得到错误`只有一个结果允许SELECT是表达式的一部分

时间:2012-12-17 08:23:47

标签: sql django

我正在尝试使用.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在dev-server上尝试。有谁知道如何解决这个问题?或者我的查询错了?

编辑:

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

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

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

    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

如果不够明确,请告诉我。

1 个答案:

答案 0 :(得分:1)

问题出在查询中。通常,在编写子查询时,必须仅返回1个结果。所以像voter_id那样的子查询:

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

无效,因为它可以返回多个结果。如果您确定它将始终返回一个结果,则可以使用max()min()聚合函数:

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个用户。