我正在尝试使用.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
如果还不够清楚,请告诉我。