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:
In PostgreSQL, a sequence is a user-defined schema-bound object which creates a sequence of integers depending on the particular requirement. In PostgreSQL sequence, the orders of numbers are important. Such as {5,6,7,8,9,10} and {10,9,8,7,6,5} are completely different sequences.
Nextval function will increment the value of the specified sequence and return the new value as an integer type. Currval will return the last returned value from Nextval functions. If we have not used Nextval, then it will not return any value. Setval in the PostgreSQL sequence will set the current value of sequences to N value.
It is an object that will use to generate a sequence number automatically. We can create the number of sequences as we like, but we need to define each sequence-unique name at the time of creation. The sequence in PostgreSQL is a special kind of object which is used to generate numeric identifiers.
Serial in PostgreSQL indicates that the value for the column is generated by consulting the sequence. Serial in PostgreSQL will create a new sequence object and set the column’s default value to the next value produced by the sequences. The sequence always produces a non-null value; it will add the not null constraints to the column.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With