0

I'm basically trying to get this SQL query working in SQLAlchemy:

SELECT p.id, (SELECT COUNT(*) FROM response r WHERE <conditions on r> AND r.prompt_id = p.id)
  FROM prompt p WHERE p.<conditions>;

I have it all working except for the reference to p.id in the subquery:

# used all over application
def filter_prompt(search_string, customer_id, state):
  prompts = Prompt.query
  if search_string:
    prompts = prompts.filter(Prompt.id.ilike('%' + search_string + '%'))
  elif customer_id, state, etc
    ... more filtering ...
  return prompts

I have a special case where I need to return the number of related objects, so I'm attempting to just add a subquery column:

prompts = filter_prompt(...)
count_subquery = session.query(func.count('response')).filter(Response.validated_at>=date, Response.prompt_id == Prompt.id).subquery()
prompts_with_response_count = prompts.add_column(count_subquery)

The problem is that Prompt.id is not properly resolved to the id for that row. How would I properly translate the above SQL to SQLAlchemy?

4

1 回答 1

1

如果在 select 语句中使用子查询,则不要执行subquery but instead doas_scalar`(它告诉 SQLAlchemy 会有一个标量结果,一行一列):

count_subquery = session.query(func.count('response')).filter(Response.validated_at>=date, Response.prompt_id == Prompt.id).as_scalar()
于 2013-10-28T22:34:25.147 回答