get next mysql autoincrement value

1
2
3
4
5
6
7
8
    def get_nextautoincrement( mymodel ):
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute( "SELECT Auto_increment FROM information_schema.tables WHERE table_name='%s';" % \
                        mymodel._meta.db_table)
        row = cursor.fetchone()
        cursor.close()
        return row[0]

More like this

  1. MySQL django password function by mcosta 4 years, 10 months ago
  2. Username filled automatically with id by djangoman 4 years, 3 months ago
  3. dumpdata/loaddata with MySQL and ForeignKeys (Revision 2) by cmgreen 6 years ago
  4. dumpdata/loaddata with MySQL and ForeignKeys by cmgreen 6 years, 3 months ago
  5. sort_by_id_sequence by simon 5 years, 11 months ago

Comments

ranedk (on April 4, 2009):

I think this might have some problems if there are multiple requests at the same time. You will get the next increment id, but before you do an insert, another requests inserts the data.

#

ludvig.ericson (on April 12, 2009):

MySQL can't do this. The only sensible thing to do here is something like PostgreSQL's series, where you have to reserve the next item to get its value (or well, it's how things are done.)

This code, as the previous poster says, is dangerous because it's up for race.

Beyond that, it doesn't use the database's own quoting mechanisms, so very exotic cases might end up making this code fail.

Further, it doesn't really handle the case where there is no auto_increment set at all. It'll result in an IndexError on line 8.

So, I'm sorry, but I think this needs to be reworked on a fundamental level.

#

(Forgotten your password?)