Trying to get the next value in sequence from a postgres DB, with django
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.execu开发者_如何学编程te("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
This code will work:
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("select nextval('winner')")
result = cursor.fetchone()
full documentation about cursor
cursor.execute
always returns None.
To get the value from the SQL statement, you have to use cursor.fetchone()
(or fetchall()
).
See the documentation, although note that this doesn't actually have anything to do with Django, but is the standard Python SQL DB API.
精彩评论