Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Change models without clearing all data?

Tags:

python

django

I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data?

I tried changing the field and running python manage.py syncdb. There was no output from this command.

Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db.

I am using SQLite.

I am able to delete the db file, then re-run python manage.py syncdb, but that is kind of a pain. Is there a better way to do it?

like image 785
Nick Heiner Avatar asked Apr 30 '10 18:04

Nick Heiner


People also ask

Is Clean called before save Django?

Note that full_clean() will NOT be called automatically when you call your model's save() method. You'll need to call it manually if you want to run model validation outside of a ModelForm. (This is for backwards compatibility.)

Are Django models Threadsafe?

Note that the Django ORM is explicitly thread-safe. There are multiple references in the documentation about threaded operation.

How do I update model fields in Django?

Method 2: Using F Expression You can also use the F expression to do the same job. Note: You have to import the F expression before using it. Basically, these are the two methods you can use to update field in Django model.


2 Answers

Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out Django South.

See the docs for syndb:

Syncdb will not alter existing tables

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

You have to change the column names in your DB manually through whatever administration tools sqlite provides. I've done this with MySQL, for instance, and since MySQL lets you change column names without affecting your data, it's no problem.

like image 103
JAL Avatar answered Oct 12 '22 07:10

JAL


Of course there is.
Check out South

like image 45
the_drow Avatar answered Oct 12 '22 07:10

the_drow