So I have this django installation in which there are a bunch of migration scripts. They look like so:
00001_initial.py
00002_blah_blah.py
00003_bleh_bleh.py
Now I know these are "database building" scripts which will take stuff defined in models.py and run them against the db to "create" tables and stuff.
I want to create a new table(so I created its definition in models.py). For this, I have copied another model class and edited its name and fields and it is all fine. Lets call this new model class 'boom'.
My question is now how do I "create" this boom table using the migration script and the boom model?
I am worried that I might accidentally disrupt anything that is already in DB. How do I run the migration to create only boom table? How do I create a migration script specifically for it?
I know that it has something to do with manage.py and running migrate or runmigration (or is it sqlmigrate?...im confused). While creating the boom table, I dont want the database to go boom if you know what I mean :)
First, create a backup of your database. Copy it to your development machine. Try things out on that. That way it doesn't matter if it does go "boom" for some reason.
The first thing to do is
python manage.py showmigrations
This shows all the existing migrations, and it should show that they have been applied with an [X].
Then,
python manage.py makemigrations
Makes a new migration file for your new model (name 00004_...).
Then do
python manage.py migrate
to apply it. To undo it, go back to the state of migrations 00003, with
python manage.py migrate <yourappname> 00003
There are two steps to migrations in Django.
./manage.py makemigrations
will create the migration files that you see - these describe the changes that should be made to the database.
You also need to run
./manage.py migrate
this will apply the migrations and actually run the alter table commands in SQL to change the actual database structure.
Generally adding fields or tables won't affect anything else in the database. Be more careful when altering or deleting existing fields as that can affect your data.
The reason for two steps is so that you can make changes on a dev machine and once happy commit the migration files and release to your production environment. Then you run the migrate command on your production machine to bring the production database to the same state as your dev machine (no need for makemigrations on production assuming that your databases started the same).
My question is now how do I "create" this boom table using the
migration script and the boom model?
./manage.py makemigrations
I am worried that I might accidentally disrupt anything that is
already in DB.
The whole point of migrations, is that it doesn't
I know that it has something to do with manage.py and running migrate
or runmigration
For more information please refer to : https://docs.djangoproject.com/en/1.10/topics/migrations/
And rest assured that your database will not go boom! :-)
I solved it simply, changing the name of the new model to the original name, and then I checked if there is the table in the database, if not, I just create a new table with the old name with just a field like id.
And then clear migrations and create new migrations, migrate and verify table was fixed in DB and has all missing fields.
If it still doesn't work, then change the model name back to a new one.
but when django asks you if you are renaming the model you should say NO to get the old one removed properly and create a new one.
This type of error usually occurs when you delete some table in dB manually, and then the migration history changes in the tables are lost.
But it is not necessary to erase the entire database and start from scratch.
Related
I have walking on a strange way, but it is result of circumstances.
I had to been generate single models.py from exist postgres DB by inspect_db.
Next I fix some field (was a few problem with keys), and create 2 apps inside this project. So now I have 3 models.py (them are split models.py, whitch was generate by inspect_db). managed = True was added. Classes have same links and datatypes like in the database
Next I wish to integrate this models to exist database. I make migration, I migrate and in the end DB have only system django tables (auth_, django_migrations etc.) None from my classes (although migrate files were create). So I tryied to delete migrations catalogs and repeat makemigrations and migrate, but terminal threw it:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
(forest-venv) user#user-HP-Z800-Workstation ~/MyProjects/forest-venv/lesoved $ python manage.py runserver 8001
Performing system checks...
If I try make migrates again - no changes. I tryied to delete info about my apps in django_migrations table - no result.
So my questions:
- It is possible to integrate new models into exist database (if names, keyes and formats is ok)?
- Integration is possible by the way where data from exist database is saved after migrations?
- How to return possobillity of make migrations? now it isn't work.
The trick when using an existing database is to make sure you start from a well-defined state: First get Django to the exact same state as your db, and only after that start making changes to your models. So these are the steps:
Check that your database doesn't have a django-migrations table, delete it using SQL if needed. (Note: I'm assuming this db isn't generated by Django to start with and you're creating a fresh django application)
Create your models with inspectdb. If needed, rename the models to have proper CamelCase. If you rename models or fields that would change the table or column name in the db, make sure to set db_table (Meta options of your model) and db_column (as field attribute).
Run manage.py makemigrations. Check the migration files for your models, just to be sure the names match with your db.
For your own apps, run manage.py migrate <app> --fake. This will add the migrations to django-migrations table in your db as if they ran, without actually running them.
Then run manage.py migrate to create the django provided tables (auth, contenttype, session etc...)
Now you are at the state where you can start changing things. If you change the model and run makemigrations it should create a migration just for your changes.
I've just started working with Django, and when setting up my models and db I picked a name which I would like to change now. Is it OK to just edit models.py (rename the class), then run makemigrations and migrate on it? I have a table set up in the db (SQLite), but no entries yet.
I'm new to database migration too. Does this cover what I want to do?
Thanks.
After renaming of model in the models.py, run makemigrations. The question should appear "Did you rename the xxx model to yyy? [y/N]" Press y and it will be enough in your case.
UPD:
In general, you should run makemigrations and migrate every time when you change code in models.py. You should manually edit migrations files (created by makemigrations) only in few cases, when the Django isn't smart enough to understand what you want to do.
Django 1.7, Python 3.4.
In my models I have several TextFields defined.
When I go to load a JSON fixture (which was generated from an SQLite3 dump), it fails on the second object, which has 515 characters for one of its fields.
The error printed is
psycopg2.DataError: value too long for type character varying(500)
I created a new database (not just a table drop, a whole new db), modified my settings.py file, ran manage.py syncdb on the new database, created a user, and tried to load the data again, getting the same error.
Upon opening pgAdmin3, all columns, both CharField and TextField defined are listed as type character var.
So it seems TextField is being ignored and CharFields are being created instead. The PostgreSQL documentation explicitly lists both text and character types, and defines text as being unlimited in length. Any idea why?
I'm not sure what the exact cause was, but it seems to be related to django's migration tool storing migrations, even on a new database.
What I did to get this behavior:
Create django project, then apps, using CharField
syncdb, run the project's dev server
kill the devserver, modify fields to be TextField
Create a new Postgres database, modify settings.py
Run syncdb, attempt to load fixtures
See the error in question, examine db instance
What fixed the problem:
Create a new database, modify settings.py
delete all migrations in apps/migrations folders
after running syncdb, also run createmigrations and migrate
The last step generated a migration, even though there were none stored in the migrations folder, and there had been no changes to models or data since syncdb was run on the new database, which I found to be odd.
Somewhere in the last two steps this was fixed. Future people stumbling upon this: sorry, I'm not going to keep creating django projects to test the behavior further, but perhaps with this information you can fix your own database problems.
The problem is pretty self-explanatory in the title. Do I need to do that or I just need to edit the existing migration file?
Yes, Django won't recognize the field if you change the name. I will say that the "field does not exist", so YES, you have to run Django's South migrate / schemamigration as you asked.
Datatype YES as well. Django may be okay at first if you only change the field type depending, but may run into problems later depending on what you have in that field.
You need to do a schemamigration every time you change your models.
On every call of python manage.py migrate command south record number of the latest migration applied into database migrationhistory table. So if you just change existing migration it won't be applied because south would think it's already applied.
You can make a backward migration, fix next migration, even delete it and make a new one and only then migrate forward.
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?
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.
Of course there is.
Check out South
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.