所以我搜索了這個到目前爲止還找不到任何答案。 我在那裏的時候,我已經把在數據庫:Django Views中的嵌套SQL查詢
SELECT event_name, team_number
FROM teams_by_event
WHERE team_number IN (SELECT team_number
FROM teams_by_event
WHERE event_name = '[user inputs event name]'
) ORDER BY team_number;
它給了我正是我要找的回報。 我的問題是,我想不出在Django視圖中執行此操作的方法,以及我嘗試過的方法,只是在Django中使用原始SQL也無法正常工作,但我得到一個語法錯誤,指出上一個括號SQL查詢無效。
views.py:
def teams_by_event(request, shorthand):
code = TeamsByEvent.objects.filter(shorthand=shorthand)
for event in TeamsByEvent.objects.raw('SELECT event_name, team_number \
FROM teams_by_event \
WHERE team_number IN \
(SELECT team_number \
FROM teams_by_event) \
WHERE shorthand= % s', [code])
print (event.team_number, event.event_name)
return render(request, 'event-info.html', {'info': info})
models.py
class TeamsByEvent(models.Model):
team_number = models.IntegerField()
event_name = models.CharField(max_length=50)
shorthand = models.CharField(max_length=12)
class Meta:
db_table = 'teams_by_event'
app_label = 'frcstats'
編輯:: 回溯:
Traceback (most recent call last):
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/alicen/git/first_robotics/frcstats/views.py", line 1034, in teams_by_event
for event in TeamsByEvent.objects.raw(raw_query):
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/models/query.py", line 1219, in __iter__
query = iter(self.query)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/models/sql/query.py", line 79, in __iter__
self._execute_query()
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/models/sql/query.py", line 113, in _execute_query
self.cursor.execute(self.sql, params)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 322, in execute
query = self.convert_query(query)
File "/Users/alicen/git/first_robotics/venv/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 330, in convert_query
return FORMAT_QMARK_REGEX.sub('?', query).replace('%%', '%')
TypeError: expected string or buffer
我可以看到你的models.py? – arcegk
@arcegk - 已編輯爲我的models.py添加該表 – alicen
您已在'%s'內有額外的空間,並且在已指出的錯誤位置處有一個右括號。 – serg