1

Using Postgresql 9.3 + PostGIS with django, I'm trying to enter a record to my table and return the given id like so

def join(request):
    from django.db import connection, transaction
    cursor = connection.cursor()
    id = cursor.execute("insert into table1 values(DEFAULT, 'temp', null,-4, null,null, null, null, DEFAULT, 1,null,DEFAULT,DEFAULT, null) returning id")
    transaction.set_dirty()

    return HttpResponse(id)

this returns None, how can i get the id that is returned from the sql query

2 Answers 2

2
from django.db import connection, transaction

def join(request):
    cursor = connection.cursor()
    id = cursor.execute("insert into table1 values(DEFAULT, 'temp', null,-4, null,null, null, null, DEFAULT, 1,null,DEFAULT,DEFAULT, null)")
    transaction.set_dirty()
    last_id = connection.insert_id()
    return HttpResponse(str(last_id))
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting an error global name 'string' is not defined also if i print last_id i get 0
Sorry about that. Fixed. Use str
Edited again, to use the connection object to get the id
now i'm getting this error: 'DatabaseWrapper' object has no attribute 'insert_id'
0

What is your database backend? If you use sqlite3,

def join(request):
    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute("insert into table1 values(DEFAULT, 'temp', null,-4, null,null, null, null, DEFAULT, 1,null,DEFAULT,DEFAULT, null)")
    cursor.execute("SELECT last_insert_rowid() FROM table1")
    id = cursor.fetchone()[0]
    transaction.set_dirty()

    return HttpResponse(id)

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.