Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to change primary keys in an existing Django app?

I have an application which is in BETA mode. The model of this app has some classes with an explicit primary_key. As a consequence Django use the fields and doesn't create an id automatically.

class Something(models.Model):     name = models.CharField(max_length=64, primary_key=True) 

I think that it was a bad idea (see unicode error when saving an object in django admin) and I would like to move back and have an id for every class of my model.

class Something(models.Model):     name = models.CharField(max_length=64, db_index=True) 

I've made the changes to my model (replace every primary_key=True by db_index=True) and I want to migrate the database with south.

Unfortunately, the migration fails with the following message: ValueError: You cannot add a null=False column without a default value.

I am evaluating the different workarounds for this problem. Any suggestions?

Thanks for your help

like image 974
luc Avatar asked Jan 13 '10 10:01

luc


People also ask

How do I change 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).

What is the best choice for a primary key?

Integer (number) data types are the best choice for primary key, followed by fixed-length character data types. SQL Server processes number data type values faster than character data type values because it converts characters to ASCII equivalent values before processing, which is an extra step.

Does Django support composite primary key?

Django does not support composite primary keys.

Does Django support multiple primary keys?

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


2 Answers

Agreed, your model is probably wrong.

The formal primary key should always be a surrogate key. Never anything else. [Strong words. Been database designer since the 1980's. Important lessoned learned is this: everything is changeable, even when the users swear on their mothers' graves that the value cannot be changed is is truly a natural key that can be taken as primary. It isn't primary. Only surrogates can be primary.]

You're doing open-heart surgery. Don't mess with schema migration. You're replacing the schema.

  1. Unload your data into JSON files. Use Django's own internal django-admin.py tools for this. You should create one unload file for each that will be changing and each table that depends on a key which is being created. Separate files make this slightly easier to do.

  2. Drop the tables which you are going to change from the old schema.

    Tables which depend on these tables will have their FK's changed; you can either update the rows in place or -- it might be simpler -- to delete and reinsert these rows, also.

  3. Create the new schema. This will only create the tables which are changing.

  4. Write scripts to read and reload the data with the new keys. These are short and very similar. Each script will use json.load() to read objects from the source file; you will then create your schema objects from the JSON tuple-line objects that were built for you. You can then insert them into the database.

    You have two cases.

    • Tables with PK's change changed will be inserted and will get new PK's. These must be "cascaded" to other tables to assure that the other table's FK's get changed also.

    • Tables with FK's that change will have to locate the row in the foreign table and update their FK reference.

Alternative.

  1. Rename all your old tables.

  2. Create the entire new schema.

  3. Write SQL to migrate all the data from old schema to new schema. This will have to cleverly reassign keys as it goes.

  4. Drop the renamed old tables.

 

like image 139
S.Lott Avatar answered Sep 22 '22 03:09

S.Lott


To change primary key with south you can use south.db.create_primary_key command in datamigration. To change your custom CharField pk to standard AutoField you should do:

1) create new field in your model

class MyModel(Model):     id = models.AutoField(null=True) 

1.1) if you have a foreign key in some other model to this model, create new fake fk field on these model too (use IntegerField, it will then be converted)

class MyRelatedModel(Model):     fake_fk = models.IntegerField(null=True) 

2) create automatic south migration and migrate:

./manage.py schemamigration --auto ./manage.py migrate 

3) create new datamigration

./manage.py datamigration <your_appname> fill_id 

in tis datamigration fill these new id and fk fields with numbers (just enumerate them)

    for n, obj in enumerate(orm.MyModel.objects.all()):         obj.id = n         # update objects with foreign keys         obj.myrelatedmodel_set.all().update(fake_fk = n)         obj.save()      db.delete_primary_key('my_app_mymodel')     db.create_primary_key('my_app_mymodel', ['id']) 

4) in your models set primary_key=True on your new pk field

id = models.AutoField(primary_key=True) 

5) delete old primary key field (if it is not needed) create auto migration and migrate.

5.1) if you have foreign keys - delete old foreign key fields too (migrate)

6) Last step - restore fireign key relations. Create real fk field again, and delete your fake_fk field, create auto migration BUT DO NOT MIGRATE(!) - you need to modify created auto migration: instead of creating new fk and deleting fake_fk - rename column fake_fk

# in your models class MyRelatedModel(Model):     # delete fake_fk     # fake_fk = models.InegerField(null=True)     # create real fk     mymodel = models.FoeignKey('MyModel', null=True)  # in migration     def forwards(self, orm):         # left this without change - create fk field         db.add_column('my_app_myrelatedmodel', 'mymodel',                   self.gf('django.db.models.fields.related.ForeignKey')(default=1, related_name='lots', to=orm['my_app.MyModel']),keep_default=False)          # remove fk column and rename fake_fk         db.delete_column('my_app_myrelatedmodel', 'mymodel_id')         db.rename_column('my_app_myrelatedmodel', 'fake_fk', 'mymodel_id') 

so previously filled fake_fk becomes a column, that contain actual relation data, and it does not get lost after all the steps above.

like image 41
user920391 Avatar answered Sep 24 '22 03:09

user920391