7

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

2 Answers 2

11

This code will work:

from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("select nextval('winner')")
    result = cursor.fetchone()

Full documentation about cursor

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.