尝试使用 django 从 postgres DB 中按顺序获取下一个值
我在数据库中定义了一个序列,我想在 django 应用程序中使用它。我假设我可以使用 django 文档中指定的原始 sql 方法: http: //docs.djangoproject.com/en/1.1/topics/db/sql/。我的计划是执行以下 SQL 语句:
select nextval('winner')
其中 winner 是我想要从中获取下一个值的序列。这是我的代码:
from django.db import connection, transaction
.....
cursor = connection.cursor()
result = cursor.execute("select nextval('winner')")
结果始终是 NoneType 对象。这看起来非常简单明了,但我还没能做到这一点。我已经在交互式控制台中尝试过,结果相同。如果我查看 connection.queries 对象,我会看到:
{'time': '0.000', 'sql': "select nextval('winner')"}
生成的 sql 是有效的。有什么想法吗?
我正在使用:
- Django 1.1
- Python 2.6
- Postgres 8.3
- Psycopg2
- Mac OSX
I have a sequence defined in my database that I want to use in my django application. I assumed I could use the raw sql method specified in the django documentation here: http://docs.djangoproject.com/en/1.1/topics/db/sql/. My plan was to execute the following SQL statment:
select nextval('winner')
where winner is the sequence I want to get the next value from. Here is my code:
from django.db import connection, transaction
.....
cursor = connection.cursor()
result = cursor.execute("select nextval('winner')")
The result is always a NoneType object. This seems pretty simple and straightforward, but I haven't been able to make this work. I've tried it in the interactive console with the same results. If I look in the connection.queries object, i see this:
{'time': '0.000', 'sql': "select nextval('winner')"}
The sql generated is valid. Any ideas?
I'm using:
- Django 1.1
- Python 2.6
- Postgres 8.3
- Psycopg2
- Mac OSX
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码将起作用:
有关 <代码>光标
This code will work:
Full documentation about
cursor
cursor.execute
总是返回 None。要从 SQL 语句获取值,您必须使用
cursor.fetchone()
(或fetchall()
)。请参阅文档,尽管请注意,这实际上与 Django 没有任何关系,而是标准的 Python SQL DB API。
cursor.execute
always returns None.To get the value from the SQL statement, you have to use
cursor.fetchone()
(orfetchall()
).See the documentation, although note that this doesn't actually have anything to do with Django, but is the standard Python SQL DB API.