I can't migrate at another database - python

I have well working project on local. I use postresql.
Ok. I create another database in postgres locally and specify new name/user/password in settings.py of project.
When I do
$ python manage.py makemigrations
I get error as
relation 'report_person' not exist
And I have tried delete (and not delete) directory 'migrations'. delete pycache. I tried specify Sqlite3 as database - but the same error.
Why I ask?
My project don't want to work with another database)
I succesfully push project on heroku. Specify parameters in settings.py. Create postgresql. But I can't make migrate on heroku) the same error.
I do makemigrations and git commit before push on heroku, but no result
Help me please.
Thank you
Have a nice day!

try migrating with --fake
python manage.py migrate --fake
python manage.py migrate yourappname --fake
and then again
python manage.py makemigrations
python manage.py migrate

Oh, I can't explain this situation. All problems in one little model.
It is from models.py:
from django import models
class Person(models.Model):
name = models.CharField(max_length=255)
position = models.CharField(max_length=255)
This part of forms.py (crazy):
from django import form
q = models.Person.objects.all()
qty = range(len(q))
PersonForm = type('PersonForm',
(forms.Form,),
{'person'+'_'+str(q[i].id): forms.BooleanField(label=q[i].name,
required=False) for i in qty})
And I must before migrations delete this 'PersonForm'. Then migrate will be succesfully in new any database. And after migrations I put this form again.
Ok. I don't undestand, why?)

Related

How to update django database models in MySQL?

How to update database table in MySQL ?
For example, in my Django app, I have a database table named 'Category1' , and I want to rename it into "Category" only.
After I run python manage.py makemigrations and python manage.py migrate , it doesn't show any errors but I can't see any changes in my MySQL Workbench.
How to do this ?
You can check if your migration has been applied with python manage.py showmigrations, you should even add the app name at the end of this command to retrieve only migration from said app: python manage.py showmigrations app_name
If it hasn't been applied you should use python manage.py migrate app_name migration_number. You replace the app_name by the name of your app and the migration_number by the 4 first digits of your migration's name.
If you change your models and then applied the associated mirgations you should have modifications in your database (that's the point of migrations).
When using makemigrations be careful, sometimes Django will understand a field being renamed as a deletion and a creation of field. In your migration you should find the method Alter field if not you should modify it by hand.

How to recreate a deleted table with Django Migrations?

There are two models Groups and Students and only one table for Groups of them, the Students table was deleted.
How to make Django recreate the deleted table? If I do makemigrations it prints "No changes detected".
On admin page when I click on the Students table it throws an exception:
relation "students_students" does not exist
In django 1.7 you can try:
1. Delete your migrations folder
2. In the database: DELETE FROM django_migrations WHERE app = 'app_name'.
You could alternatively just truncate this table.
3. python manage.py makemigrations
4. python manage.py migrate --fake
If you are working in django 1.9.5 this is the 100 % solution for this problem:
1. Delete your migrations folder
2. In the database: DELETE FROM django_migrations WHERE app = 'app_name'.
You could alternatively just truncate this table.
3. python manage.py makemigrations app_name
4. python manage.py migrate
This works 100% for me!
Jan 2021
I had a migration problem and I had to drop/delete a table by pgadmin. Then, when I makemigrations and migrate the table wasn't recreated. In this way, I've found this procedure which worked for me:
python manage.py migrate --fake app_name zero
python manage.py migrate app_name
[NOTE]
If you don't have the intended migration file, create that before the above commands by python manage.py makemigrations
If you don't want to roll back to the initial(zero) state use the number of migration file instead of zero, e.g. python manage.py migrate --fake myappname 0005
I tested this approach in Django 2.2
Read More
There isn't an easy way to get Django to recreate a table that you have deleted manually. Once your database is altered manually, Django's view of the database (from migrations) is different from reality, and it can be tricky to fix.
If you run the sqlmigrate command, it will show you the required SQL to create the table. You can run the sql in a database shell. Assuming your app name is students, and the migration that created the table was 00XX_create_students.py, you would do:
./manage.py sqlmigrate students 00XX_create_students
Be careful if there are foreign keys to or from the students table, the constraints will have to be created as well.
The only way that worked for me:
rm -r <app-name>/migrations/
python manage.py makemigrations <app-name>
python manage.py sqlmigrate <app-name> 0001_initial
Copy what it prints out (or, depending on what you have actually removed from the DB, only part of the SQL queries).
Apply those copied queries to your DB:
psql -U user_name -h 127.0.0.1 database_name
Paste what you have copied from the SQL queries printout.
Commit the queries.
And that's it - your missing tables are created.
The answer that worked for me is as follows:
Assume in your database a table of a model has been deleted and you need to re-create, then do the following.
comment out the model in models.py that creates the table that has been deleted (either the model class or a line that creates a table like a = models.ManyToManyField(...))
run: python manage.py makemigrations <app-name>, where <app-name> is the name of of the app where you have models.py
run: python manage.py migrate --fake <app-name>
un-comment the model in models.py
run: python manage.py makemigrations <app-name>
run: python manage.py migrate <app-name> (without the --fake)
and you the table should be back in the database. But any data that was in the table will be lost.
Delete the migration folder from your migration app folder and simply run the migration commands:
python3 manage.py makemigrations appname
python3 manage.py migrate
I just deleted my migrations folder, dropped the whole database, then i made migration for the app
python3 manage.py makemigration
python3 manage.py migrate
and it came back.
Rename the deleted table name to some_new_name in the models.py and run:
python3 manage.py makemigration
python3 manage.py migrate
again rename the some_new_name table to the original name and run
python3 manage.py makemigration
python3 manage.py migrate
finally, go to the dbshell and drop the table some_new_name
I create table manualy and it helps.
For Django 1.10.4
I deleted the db.sqlite3 file from the project folder and then ran the following commands:
python manage.py makemigrations app_name
python manage.py migrate
Django 1.11.2 using MariaDB, accidental drop of database table.
To recreate table, try the following:
1/ Delete all except for init.py in your app/migrations directory
2/ select * from django_migrations; delete from django_migrations where app = 'yourapp';
3/ Check your model is good and run: python manage.py makemigrations
4/ python manage.py migrate
Works for me!
if you have created your classes and performed the migration operation, and then you want to add items to your classes, empty the migration folder with this command beforehand.
In Django 3, I proceeded according to the following steps and it worked 100%
python manage.py makemigrations appname --empty
python manage.py makemigrations appname
python manage.py migrate
Actually, the above methods did not work for me, so I just perform the below workaround as I did not want to manually write the whole query to create the table.
So I changed the database in the settings file and re-ran the migrations command after deleting the migrations folder, then just performed the python migrate command it created new tables in another database then from there just opened the table in query view, copied the script, and inserted the table in my main database.
Another Simple way to do this is
Go to your migrations folder.
Search for the file which contains the code to create the Students table in DB.
Remove the code snippet from the file and save it.
Then run py manage.py makemigrations and py manage.py migrate again
This worked for me :)
In this case, you need to trick django!
Do one thing...
copy the "students" model in models.py with other name like
"studentscopy".
Now run --> python manage.py makemigration
It will create a new migration in migration package of your app. Open
that last migration and rename "studentscopy" back to "students"
in that file.
Now run --> python manage.py migrate
It will create the table again with "students" name and at last delete that "studentscopy" model from your models.py file.
Below steps solved the problem for me
Delete all migrations files
python manage.py makemigrations (Create your initial migration file 0001_inital.py)
python manage.py migrate --fake <app_name> zero
( Tell Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema. This brings the migrations to zeroth state. Otherwise Django will think there's no change to apply )
python manage.py migrate

Django 1.8 OperationalError: no such column:

I'm using django 1.8 and I'm having problems adding to my models.py. Currently it's:
from django.db import models
# Create your models here.
class Company(models.Model):
role = models.CharField(max_length=32, blank=True)
name = models.CharField(max_length=70, blank=True)
and it works perfectly fine but whenever I try to add to this and then run the server I get
OperationalError: no such column [added element]
For example I added founder = models.CharField(max_length=200, blank=True) and I ran the program and I got
django.db.utils.OperationalError: no such column: companies_company.founder
Run in your console this commands:
manage.py makemigrations app_name
manage.py migrate app_name
Every time when you change model in your app you should migrate changes to your db using makemigration and migrate commands. When you adding a new column to your db table you must add value of this column to all existing rows. You can do it by seting default value in your new field in your model.
Or set values when run migrate command ( django automatically propose this)
You can read about this in docs
This type of problem occurs when there are some operations on the model field in some other files such as forms.py or views.py other than models.py when you run makemigrations. If you read the traceback carefully you can figure it out from which file the problem is originating.
For example, if the traceback tells you some complaints in forms.py which may happen to use some of the model fields, just comment out the code that is working on the model fields and rerun makemigrations again. Hopefully it resolves the issue.
If it does, you can then remove the comments that you added before.
You have to re sync the database using python manage.py makemigrations
Maybe not optimal, but it worked for me doing that (and the default thing did not work):
delete all files apart from the init.py in migrations folder
delete the db.sqlite file
doing: python manage.py runserver (without this one previous to migrate, migrations, that did not work, I think it's linked to the views / templates calling tags, so has to run first)
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
python manage.py createsuperuser
I found that clearing all data with python3 manage.py sqlflush and then python3 manage.py flush
Then makemigrations, sqlmigrate, and then migrate
It will delete all data in the SQL database including users and objects

Django : Table doesn't exist

I dropped some table related to an app. and again tried the syncdb command
python manage.py syncdb
It shows error like
django.db.utils.ProgrammingError: (1146, "Table 'someapp.feed' doesn't exist")
models.py
class feed(models.Model):
user = models.ForeignKey(User,null=True,blank=True)
feed_text = models.CharField(max_length=2000)
date = models.CharField(max_length=30)
upvote = models.IntegerField(default=0)
downvote = models.IntegerField(default=0)
def __str__(self):
return feed.content
What I can do to get the tables for that app ?
drop tables (you already did),
comment-out the model in model.py,
and ..
if django version >= 1.7:
python manage.py makemigrations
python manage.py migrate --fake
else
python manage.py schemamigration someapp --auto
python manage.py migrate someapp --fake
comment-in your model in models.py
go to step 3. BUT this time without --fake
For those that may still be having trouble (like me), try this out:
Comment out all the URL's in the main app's urls.py
Then go ahead and run migrations:
$ ./manage.py makemigrations
$ ./manage.py migrate
The problem was alleviated by removing the ()'s
solved_time = models.DateTimeField('solved time', default=timezone.now())
to
solved_time = models.DateTimeField('solved time', default=timezone.now)
I got this answer from reddit
What solved my problem in situation when manage.py setmigration and then migrate to the SQL database is not working properly did is following:
Run command : python manage.py migrate --fake MyApp zero
After that: python manage.py migrate MyApp
And the problem that rises with connections.py and and after running correctly the migration command is solved! At least for me.
I'm using Python (3.x), MySQL DB, Django (3.x), and I was in situation when I needed after some time of successfully creating tables in my database, that some error regarding connections.py raises. But, above commands helped. I hope they will help all those who are having these type of problems.
I just ran migrations with the name of the app attached, for all the apps I had provisioned and that worked.
e.g. python3 manage.py makemigrations my_custom_app
After running for all of them I ran a migrate command to seal the deal.
python3 manage.py migrate. That was it. I'm still wondering why django behaves this way sometimes though.
none of the above solutions worked for me, I finally solved by
sudo systemctl stop mysql.service
sudo apt-get purge mysql-server
sudo apt-get install mysql-server
sudo systemctl stop mysql.service
In my case the code that I pulled had managed = False and I wanted the tables to be maintained by Django.
But when I did makemigrations the custom tables were not being detected or I was getting the error that the app_name.Table_name does not exist
I tried the following:
delete all the migration files inside the migrations folder (except init.py file) and then makemigrations then finally migrate
above 2 answers
this
PS: This solution is only feasible if backup is present or data is not important or you are just started creating the tables, as purging mysql will lead to loss of data
This is linked to the migration data in the scripts inside the project not matching with the migration scripts in the database as far as I could tell.
I solved this by the following steps :
Delete all the migration scripts under migration folder except __ini__
Make sure that the model.py contains the same structure as the table in the database and managed=True
Remove all Django Created tables like auth_user,... etc
Run the following code
$ ./manage.py makemigrations
$ ./manage.py migrate
This will create the migration scripts again and will apply it to your database.
I had this issue where I was playing with same database structure in production vs development. While dropping and recreating tables will probably resolve the issue, its worth checking your database itself and see if the model is actually correct. For myself I created the development database incorrectly with the table names all in lowercase while in production the first letter of tables were capitalized. I used the python manage.py inspectdb command on production db, and compared it to the model and realized that in the model it was trying to insert data to table 'test' instead of 'Test' for example. Hope that helps some of you in future.
I had a similar issue.
I had another python (with a class) file which need access to DB.
For some reasons, when running 'makemigrations' this file was processed (I guess this is linked to some import chains).
In this class, I had a method containing a default arg method(defaultModel=Model.get_default()) in the signature which was accessing to the default object in the DB (static method included in the Model class).
A the import time, this default arg was evaluated and as the table is not populated yet, it gives this error.
So I just set None for the default args and asks for the default model object inside the method. This solved the issue.
I have to face same issue and there are a couple of approaches, but the one I think is the most probable one.
Maybe you are loading views or queries to database but you havenĀ“t granted enough time for Django to migrate the models to DB. That's why the "table doesn't exist".
Make sure you use this sort of initialization in you view's code:
Class RegisterForm(forms.Form):
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
A second approach is you clean previous migrations, delete the database and start over the migration process.
I tried all of the above tricks and never worked for me.
I commented on all imports and URLs that called a particular Table
In this solution, your data will be removed. I removed the app and created the app again. I copied the app folder somewhere and delete the app folder from my project. I commented on all lines in urls.py and files similar views.py and admin.py that use this app. also app name in settings.py.
In mysql:
truncate django_migrations;
truncate django_admin_log;
Do this for all models in your app and change n.
n is app id.
delete from auth_permission where content_type_id=n
delete from django_content_type where app_label='appname'
python manage.py startapp your_app_name
Then uncomment previous lines and restore files and run
python manage.py makemigrations
python manage.pt migrate
I faced the same problem, some of the above mentioned answers seemed not to work for me, but here's a simple 4 step solution:
1) Delete the migrations files below __init__.py (don't delete __init__.py) in your specific app.
2) python manage.py makemigrations AppName
3) python manage.py migrate --fake AppName zero
4) python manage.py migrate AppName
Hope these works for you.
I faced the same issue earlier when I accidentally deleted my migrations folder in an app. I was able to fix it by running manual makemigrations for that specific app.
Here's the fix for Windows,
py manage.py makemigrations <your_app_name>
py manage.py migrate
For other OS you need to replace py with python3 or python
I hope this helped fix your issue!
if the python manage.py migrate still doesn't work I mean when you do this it nothing do anything you can delete the app's migrations from django_migrations table after then do
python manage.py migrate

South Migration Issues

I have looked at these questions; http://south.readthedocs.org/en/latest/tutorial/part1.html, South ignores change in field default value in Python / Django & Django-south not detecting DB changes and many more all over SO but I can't seem to fix my problem.
I have an existing model with data in it's tables, and I'm adding another model via Foreign key to it. I have run schema migrations and migrations, but nothing has proved to work. This is the code:
class UserNote(models.Model):
user = models.ForeignKey(User)
description = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserNoteType(models.Model):
name = models.CharField(max_length=20)
I need to add UserNoteType to UserNote as Foreign key,and every attempt to add the field results in "not installed", "not defined". I've been battling with this for hours now, any help would assist greatly.
EDIT:
Error I recieve when I try create a Schema-migration:
CommandError: One or more models did not validate:
auth.usernote: 'note_type' has a relation with model , which has either not been installed or is abstract.
Have you tried to convert your existing app for South with the following command ?
python manage.py convert_to_south my_app
More informations can be find here
The UserNote model was attached to the Django UserAuth application. This resulted with South looking in the wrong application each time. I fixed this issue by creating a custom command to manually insert the new column note_type to the UserNote table.
Thank you so much for your help.
For your reference
If you are creating new project, beginning it's self you need to setup south, Try below:
python manage.py syncdb
python manage.py schemamigration --initial firstapp
python manage.py migrate forecasts --fake
python manage.py schemamigration --auto firstapp
python manage.py migrate google
After the development side you are planning to include south, then try below
./manage.py schemamigration --auto firstapp
./manage.py migrate firstapp

Categories