Opened 11 years ago

Closed 11 years ago

#20588 closed Bug (invalid)

TypeError: 'NoneType' object has no attribute '__getitem__' in fetch_returned_insert_id function

Reported by: tazo90@… Owned by: tazo90
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords: psycopg2, fetch_returned_insert_id
Cc: tazo90@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 137, in create
    return self.get_query_set().create(**kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 377, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 463, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 551, in save_base
    result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 203, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1593, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 914, in execute_sql
    return self.connection.ops.fetch_returned_insert_id(cursor)
  File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 548, in fetch_returned_insert_id
    return cursor.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

It happened when I was trying to use plpgsql trigger from custom sql that returned NULL.

The error means we tried to do something like None[0]. In the backtrace, it says return cursor.fetchone()[0], which means that your cursor.fetchone() is None.

Fix code, you have to change:

return cursor.fetchone()[0]

from C:\Python27\lib\site-packages\django\db\backends\init.py", line 548, in fetch_returned_insert_id to:

res = cursor.fetchone()
if res:
     return res[0]
else:
     return None

After that change, everything is working.

Change History (2)

comment:1 by tazo90, 11 years ago

comment:2 by Anssi Kääriäinen, 11 years ago

Resolution: invalid
Status: newclosed

I don't think the proposed change is correct. For create() to work as specified it needs to set the primary key value unless that is already set. The proposed change silently lets create() skip setting the primary key value. Errors should never pass silently, unless explicitly silenced. I think you can actually silence this in 1.6 by overriding the _do_insert() method (internal API).

Note: See TracTickets for help on using tickets.
Back to Top