Django Raw查询用法

时间:2016-09-19 19:42:49

标签: python mysql django

我正在努力使用原始查询的输出。我的代码如下:

cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2")
currentSelectedTeams = cursor.fetchone()

if not currentSelectedTeams:
    currentSelectedTeam1 = 0
    currentSelectedTeam2 = 0
else:
    currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
    currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid

我收到以下错误:

currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
AttributeError: 'long' object has no attribute 'teamselectionid'

任何帮助都会受到赞赏,非常感谢,Alan。

PS

如果它有助于我在MySQL中查询的结果如下:

mysql> select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2;
+-----------------+-------------------+-----------------+---------+
| fixturematchday | teamselection1or2 | teamselectionid | user_id |
+-----------------+-------------------+-----------------+---------+
|               6 |                 1 |              31 |     349 |
|               6 |                 2 |              21 |     349 |
+-----------------+-------------------+-----------------+---------+
2 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:2)

您的问题是您是using cursor.fetchone()并迭代结果,期望它返回多行。

如果您想获得前2个结果,则可能需要使用fetchmany and limit to 2 records instead

这就是幕后发生的事情:

由于您只提取了一条记录,currentSelectedTeams[0]实际上正在返回fixturematchday列,它看起来像long类型,您无法从中访问该属性。

另一种选择是使用pretty powerful Django ORM来获取此查询结果

编辑:

如果您真的想坚持基于cursor的实施,请尝试以下方法:

cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2 LIMIT 2")
#Note the LIMIT 2

currentSelectedTeams = cursor.fetchall()

if not currentSelectedTeams:
    currentSelectedTeam1 = 0
    currentSelectedTeam2 = 0
else:
    currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid
    currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid

请注意,在边缘情况下,只返回一行,此实现将失败。 (您需要检查光标返回长度等。)

如果这是一个django queryset实现,它看起来像这样:

qs = Fixture.objects.filter(..).values("fixturematchday", "userselection__ teamselection1or2", "userselection__teamselectionid", "userselection__userid")[:2]