关于Postgresql的Django:使用原始sql插件,返回语句不起作用

时间:2013-12-23 16:10:30

标签: sql django insert

使用Postgresql 9.3 + PostGIS与django,我正在尝试输入一个记录到我的表并返回给定的id如此

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)

这会返回None,如何获取从sql查询返回的id

2 个答案:

答案 0 :(得分:1)

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))

答案 1 :(得分:0)

您的数据库后端是什么?如果你使用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)