How can i know the next free primary key of some model?
Even if you can query the next available primary key value, it wouldn't help you. Unless you lock the table, you can't use that value before some other database client might grab it for their insert.
Instead, you should just insert your row, and then you can query the most recent key value generated during your current session. Every database that supports auto-generated primary keys provides a method to retrieve the most recent key inserted during your session.
The "during your session" part is important because it shields your session from any inserts being done concurrently by other clients. They can generate key values and your session will continue to report the same value it inserted most recently.
@Stuart Childs supposes that MySQL generates the next ID with MAX(column_name)+1
but this is incorrect. Say you insert a row and an ID value is generated. But you rollback this insert, or subsequently DELETE
that row. The next time you insert, MySQL will generate a brand new ID value. So the ID value is one greater than the last ID value generated by any client, regardless of what rows are currently stored in the table.
Likewise if you insert but don't commit immediately. Before you commit, some other client does an insert. Both your session and the other client's session will have their own unique ID value generated. Auto-generated primary keys operate without regard to transaction isolation, to ensure uniqueness.
Auto-generated primary key values are not re-used or allocated to more than one session, even if you have not yet committed your insert, or if you rollback the insert, or if you delete the row.
next_id = User.objects.order_by('-id').first().id + 1
Might need to handle if none exists.
Or with a max query:
from django.db.models import Max
users = User.objects.all()
#might be possible model has no records so make sure to handle None
next_id = users.aggregate(Max('id'))['id__max'] + 1 if users else 1
-Using Django and Mysql
next_id = Table.objects.filter(id__gt = current_id)[0].id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With