Django 1.8rc1 migrate not recreating tables - django

I'm using Django 1.8rc1. I made a change to some models and ran into an issue so I decided to back up and just recreate all of my models. I'm in the early stages so a complete rebuild of the database is no issue.
After removing all the migration files in my app/migrations folder, I did a makemigrations, which showed that three new tables have to be created:
Migrations for 'track':
0001_initial.py:
- Create model Milestone
- Create model Project
- Create model Task
But then the migrate doesn't do the create tables step for some reason.
$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: messages, staticfiles
Apply all migrations: auth, sessions, track, admin, contenttypes
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
No migrations to apply.
I would think deleting the migration files would remove the history of tables ever being created and would force Django to re-run the CREATE TABLE statements. Any idea why it isn't?

The resolution for me was to delete the migrations directory from the offending app, (and I did a mkdir migrations just in case it was required) and then reran:
python manage.py makemigrations
python manage.py migrate
That worked great, and I could see that the tables were created.

Here's the workaround:
Delete the db.sqlite3 file from your project source folder and run the migrations again.
Sometimes, when you modify models and run migrations django doesn't apply it smoothly. Not an issue, you could use South from next time.

Django will create history in django_migrations. You need to clean it first then use those commands to generate your tables.
So try to go to your database and find the table django_migrations. Delete all the rows which have app equals your app name. For example
id app name applied
20 track 0001_initial 2016-01-13 02:55:23
Then do a makemigrations & migrate should work.

Related

Django makemigrations adds a new file to migrations folder, however, migrate command doesn't do anything

I just added a new field to a database model in my django app. When I run makemigrations, I see that a new migration file is created, however, running python manage.py migrate doesn't do anything.
(twisto-pU_5F16G-py3.10) ➜ twisto git:(burakhan-ze-204-trverification-serrvisine-gizlilik-politikasi-eklenmesi) python manage.py makemigrations customer
Migrations for 'customer':
apps/customer/migrations/0221_trupgraderequest_privacy_policy_doc_uuid.py
- Add field privacy_policy_doc_uuid to trupgraderequest
(twisto-pU_5F16G-py3.10) ➜ twisto git:(burakhan-ze-204-trverification-serrvisine-gizlilik-politikasi-eklenmesi) ✗ python manage.py migrate
Operations to perform:
Apply all migrations: abtest, account, accounting, admin, api, auth, banking, campaign, card, career, cash, change_requests, collectora, contenttypes, customer, dealerpanel, documents, feedback, gdpr, heureka, homepage, kyc, land, partner, postdeploy, product_category, psp, request, risk, saltedge, scoring, sessions, shopping, spi, support, treehorn
Running migrations:
No migrations to apply.
Check table django_migrations.
If you have file in "migrations" folder and migrate does not do anything, that means one of two reasons:
migration is already in database;
you have deleted previous migration file with same number, so Django ignores it.
can you try delete file in folder migartons like 0001_.py all , and do migrations again.

Django manage.py: Migration applied before its dependency

When running python manage.py migrate I encounter this error:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration
<appname>.0016_auto_<date2>_<time2> is applied before its dependency
<appname>.0001_squashed_0015_auto_<date1>_<time1>
running showmigrations returns:
<appname>
[X] 0001_squashed_0015_auto_<date1>_<time1> (15 squashed migrations)
[X] 0016_auto_<date2>_<time2>
[ ] 0017_<modelname>_squashed_0019_auto_<date3>_<time3> (3 squashed migrations)
I was trying out django-extensions yesterday, when it all got messed up after me running some direct SQL queries and I reset hard using git. I'm still learning about migrations, so I don't understand what is wrong, since it seems to me that both migrations already have been applied.
Thank you for your help!
This worked for me. I thank my coworker for sharing this knowledge after I searched online for many hours.
Start your db shell
python manage.py dbshell
Use the database you want. If you don't know, run .databases (SQLite) or SHOW databases
mysql>use <database_name>;
Retrieve all the migrations under your app
mysql> select * from django_migrations where app='<app>';
You will see the output with ids next to all migrations. Look at the migration you want to drop. Say the id is 361
mysql> delete from django_migrations where id=361;
You have squashed the migrations, so one of the dependencies that 0016_auto_<date2>_<time2> had is now part of the newly created squashed migrations. Meanwhile the 0016_auto_<date2>_<time2> has already been run and now you're trying to run the squashed migration.
I personally don't know if there's any way to fix this automatically. You will need to fix the issues yourself. If you have version control, revert these changes and try to rethink how you should squash the migration without affecting old ones.
I have solved this problem when i did (custom user model) by this steps:
delete this file :
migrations\0001_initial.py
delete this :
db.sqlite3
put this code in settings.py :
AUTH_USER_MODEL = 'users.CustomUser'
Then do (makemigrations) then (migrate )
run server .. the problem solved :)
i have used this link it is help me to solve the problem of dependency :
https://docs.djangoproject.com/en/3.1/topics/auth/customizing/
Due to limitations of Django’s dynamic dependency feature for swappable models, the model referenced by AUTH_USER_MODEL must be created in the first migration of its app (usually called 0001_initial); otherwise, you’ll have dependency issues.
In addition, you may run into a CircularDependencyError when running your migrations as Django won’t be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your user model into a second migration. (You can try making two normal models that have a ForeignKey to each other and seeing how makemigrations resolves that circular dependency if you want to see how it’s usually done.)
run this python manage.py dbshell
INSERT INTO public.django_migrations(app, name, applied)
VALUES ('YOUR_APP_NAME, '0017_<modelname>_squashed_0019_auto_<date3>_<time3>', now());
and you should be fine. If Your migration was changing a lot to the database, then I am afraid it won't be that easy to fix it.
you need to fake migrations and migrate again
just make sure that you have a backup from your data because when you migrate again you need to delete apps table.
make sure that you look at show migrations and migrate un migrated apps by its sequence
Edit the dependencies of the conflicting migration, so that it no longer references the already applied migration.
Then run python manage.py migrate again and it should be fixed.
Warning: this only work suppossing that the state of the database matchs the state you get having applied the conflicting migration.
I had the same issue on 2020 with Django 3.0.6.
I tried all the relevant answers with no success. So I went in my database and deleted all the tables. You must export the relevant tables if you have done lot of work. I mainly delete django files in my database. And after, run:
python manage.py makemigrations <my-app>
And:
python manage.py migrate
Export your relevant tables if any.
First back up your database before resolving the conflicts, (Use "python manage.py dumpdata > db.json" for SQLite).
Execute python manage.py dbshell, to access the database.
Delete the migrations rows that are having conflicts from the django_migrations table.
Rename the tables conflicting in the database
Execute the makemigrations and migrate commands
After successful migrations, Drop the newly readded tables and finally restore the previously renamed tables to match the migrations need
I had the same problem, and here's how I solved it.
The following is my error message
File "/usr/local/lib/python3.11/site-packages/django/db/migrations/loader.py", line 327, in check_consistent_history
raise InconsistentMigrationHistory(
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration aaaa.0024_campaign_template is applied before its dependency bbbb.0005_templatemodel_from_template on database 'default'.
My solution
python manage.py migrate bbbb
python manage.py migrate
Because I changed the Django's app name in batches, the application order was not consistent when applied to the database. The bbbb that aaaa relies on was not created first, so I manually created the bbbb first
Migration file is not created for all app:
step 1:
create migration folder and add __init__.py file for all app
step 2:
delete db.sqlite3 database
step 3:
python manage.py migrate
python manage.py makemigrations
Delete all of your migrations folder
Delete the database(sqlite3)
Then run the makemigrations and migrate command
Delete the migration files.
Run:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
python manage.pyrunserver

What is the command to force all migrations in Django?

I switched database names, and now my Django models are out of sync with my database tables. What is the command to force Django to perform all migrations to sync up the models and the tables? I don't want manage.py migrate --fake.
I fixed this by manually deleting all the migrations and running makemigrations again to get a new initial migration file. Then, I went into my database and manually dropped all the tables that Django created in the app. Finally, I deleted all of the rows in the table django.migrations that included the app name. After all that, I ran manage.py migrate and the database was in sync.
When you change something in your models you must execute:
python manage.py makemigrations
for creation new changed schema of your models. Then:
python manage.py migrate <app_name>

Why there is no migrations detected but I just created new migrations?

This is my workflow, everything seems nice and tidy with makemigrations and migrate. However, I want to start over with my models, so I:
rm -rf all the migrations file in the django app directory;
drop all the related tables in the database;
makemigrations results in new migration files;
But when I want to migrate it into database, it is said No migrations to apply. I think the mechanism behind migrations is that models -> migrations -> database changes, if I drop the latter two it should go over again. Unfortunately it is not.
Django == 1.8.2
CLOSED There is a table called django-migrations tracking all the changes and delete related records and then I could make migrations. Thx to those who helped!
There's another table that keeps track of which migrations have been ran for each app, django_migrations. You'll have to reset that in order for django to know you have started over.
if you changed the database already then try running
python manage.py migrate <app> --fake zero

Django 1.8 - what's the difference between migrate and makemigrations?

According to the documentation here:
https://docs.djangoproject.com/en/1.8/topics/migrations/ it says:
migrate, which is responsible for applying migrations, as well as unapplying and listing their status.
and
makemigrations, which is responsible for creating new migrations based on the changes you have made to your models.
From what I understand, I first do
makemigrations
to create the migration file and then do
migrate
to actually apply the migration?
Do note though that I just began my Django project and I added my app to my "installed_apps" list. After that, I did
python manage.py runserver
and it said
You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them.
It didn't mention anything about running makemigrations.
According the Polls tutorial:
python manage.py makemigrations <app>: Create the migrations (generate the SQL commands).
python manage.py migrate: Run the migrations (execute the SQL commands).
As Django's documentation says Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps' model which you add in installed apps.It does not execute those commands in your database file. So tables doesn't created after makemigrations.
After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which has been generated by makemigrations.
migrate executes those SQL commands in database file.So after executing migrate all the tables of your installed apps are created in your database file.
You can conform this by installing sqlite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command.
As we know Django is an ORM (Object Relational Mapping). When we use the command:
python manage.py makemigrations [app_name]
It will generate the sql command to create the table corresponding to each class you made in models.py file.
then the command:
python manage.py migrate [app_name]
will create the table in database using the commands which have been generated by makemigrations.
For example, if we make a model class-
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
The corresponding sql command after using makemigrations will be
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
and using above command, table will be created in the database when we use migrate.
You should run the command -migrate- after adding a new app under the INSTALLED APPS section in the settings.py file in order to synchronize the database state with your current set of models. Assuming you've already modified the models.py file.
When you run -makemigrations- it packages up changes to your model into individual migration files.
Normally you would first run makemigrations and then migrate.
See documentation on Django Models
It is necessary to run both the commands to complete the migration of the database tables to be in sync with your models.
makemigrations simply analyzes your current models for any changes that would be out of sync with your database and creates a migrations file that can be used to bring the in sync. If left at this point, your models would still be out of sync with your database possibly breaking your code that queries the database.
migrate is the command to "Make It So!" and apply the changes noted during the makemigrations phase.
Source
This is django's replacement for the old manual south way of making migrations, they can be used to catalog changes in your models and write out changes that will take place in the db.
Migrate is basically the old syncdb but it takes into account all the migrations made by makemigrations.
makemigrations: creates the migrations (generating SQL Command- not yet executed)
migrate: run the migrations (executes the SQL command)
But in your case, Django is asking you to migrate the DEFAULT migrations which should run before first running of server. This would have been the same warning without even creating the first app.
Make migrations : Basically it generate SQL Commands for preinstalled apps and newly created app model which you added in installed app. It dose not executed SQL commands in your database. So actual tables are not created in DB.
Migrate : Migrate execute those SQL commands which are generated by make-migration in Database file . So after migrate all the tables of installed app are created in DB.
According to the second tutorial of the django tutorial series. Migrations are:
The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.
So pretty much all it does is:
When you execute the make migrations command you're saving the 'instructions' to mysql
When you execute the migrate command, you're executing those same instructions