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
- Database file storage by powerfox 4 years, 3 months ago
- PK->objects in view signature by AdamKG 5 years, 1 month ago
- load m2m fields objects by dirol 2 years, 11 months ago
- slug filename by willhardy 3 years, 10 months ago
- Field map for models by tomzee 5 years, 4 months ago
Comments
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.
#
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.
#