Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Django AutoFields to start at a higher number

Tags:

For our Django App, we'd like to get an AutoField to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas?

like image 415
user9845 Avatar asked Sep 22 '08 21:09

user9845


People also ask

How do I set primary key in Django?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

How do you Autoincrement a field in Django?

If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. A list of validators to run for this field. See the validators documentation for more information. If True, this field must be unique throughout the table.

Does Django support multiple primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

What is _( in Django?

In Django _() is an alias to ugettext(). This is covered in the django docs. I'm aware that _() is used, by convention, as an alias to ugettext() in Python code, but not in templates. And since we all don't put something like from django.


2 Answers

Like the others have said, this would be much easier to do on the database side than the Django side.

For Postgres, it'd be like so: ALTER SEQUENCE sequence_name RESTART WITH 12345; Look at your own DB engine's docs for how you'd do it there.

like image 123
AdamKG Avatar answered Sep 27 '22 22:09

AdamKG


For MySQL i created a signal that does this after syncdb:

from django.db.models.signals import post_syncdb from project.app import models as app_models  def auto_increment_start(sender, **kwargs):     from django.db import connection, transaction     cursor = connection.cursor()     cursor = cursor.execute("""                                 ALTER table app_table AUTO_INCREMENT=2000                             """)     transaction.commit_unless_managed()  post_syncdb.connect(auto_increment_start, sender=app_models) 

After a syncdb the alter table statement is executed. This will exempt you from having to login into mysql and issuing it manually.

EDIT: I know this is an old thread, but I thought it might help someone.

like image 28
Gabriel Samfira Avatar answered Sep 27 '22 22:09

Gabriel Samfira