【问题标题】:Trying to get the next value in sequence from a postgres DB, with django尝试使用 django 从 postgres DB 中按顺序获取下一个值
【发布时间】:2011-07-23 23:38:09
【问题描述】:

我在我的数据库中定义了一个序列,我想在我的 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

【问题讨论】:

    标签: sql django postgresql


    【解决方案1】:

    此代码将起作用:

    from django.db import connection, transaction
    
    cursor = connection.cursor()
    cursor.execute("select nextval('winner')")
    result = cursor.fetchone()
    

    full documentation about cursor

    【讨论】:

      【解决方案2】:

      cursor.execute 总是返回无。

      要从 SQL 语句中获取值,您必须使用 cursor.fetchone()(或 fetchall())。

      请参阅the documentation,虽然请注意这实际上与 Django 没有任何关系,而是标准的 Python SQL DB API。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-29
        • 2020-05-11
        • 2021-12-15
        • 1970-01-01
        相关资源
        最近更新 更多