Django: Change models without clearing all data?

前端 未结 3 1929
孤城傲影
孤城傲影 2021-02-05 11:37

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

相关标签:
3条回答
  • 2021-02-05 12:16

    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.

    0 讨论(0)
  • 2021-02-05 12:17

    You'll have to manually update the database schema/layout, if you're only talking about adding/removing columns.

    If you're attempting to rename a column, you'll have to find another way.

    You can use the python manage.py sql [app name] (http://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname) command to see what the new SQL should look like, to see what columns, of what type/specification Django would have you add, and then manually run corresponding ALTER TABLE commands.

    There are some apps/projects that enable easier model/DB management, but Django doesn't support this out of the box, on purpose/by design.

    0 讨论(0)
  • 2021-02-05 12:27

    Of course there is.
    Check out South

    0 讨论(0)
提交回复
热议问题