I just added the num object, and tried adding it to my admin, but I get the following error: Exception Value:
no such column: game_riddle.num
Here is the class:
class Riddle(models.Model):
"""represents a riddle, comprising a question and hints"""
world = models.ForeignKey(World)
question = models.TextField()
num = models.IntegerField()
I have a small database and the last time I added the object I had to run:sqlclear and then syncdb
How can I fix my bug without clearing the database?
Read this documention: http://south.readthedocs.org/en/0.7.6/installation.html
easy_install South
After install, put 'south' in your installed_app in settings
Don't forget to sync: python manage.py syncdb
Run this command: python manage.py schemamigration app_name --auto
The migrate: python manage.py migrate
That's it. Next if you add new model or have changes. Just do step 5 and 6 and your model will be updated.
You will need to use a migration tool such as South:
South brings migrations to Django applications. Its main objectives
are to provide a simple, stable and database-independent migration
layer to prevent all the hassle schema changes over time bring to your
Django applications.
Related
I run python manage.py makemigrations and I get:
No changes detected
Then, python manage.py migrate and I get:
No migrations to apply.
Then, I try to push the changes to production:
git push heroku master
Everything up-to-date
Then, in production, I repeat the command:
heroku run python manage.py migrate
No migrations to apply.
Just in case, I run makemigrations in production:
heroku run python manage.py makemigrations
No changes detected
WHY then I get a
ProgrammingError at ....
column .... does not exist
"No changes detected" means the database is coherent with the code.
How can I debug this?¡?
I got the same problem (column not exist) but when I try to run migrate not with makemigrations (it is the same issue I believe)
Cause: I removed the migration files and replaced them with single pretending intial migration file 0001 before running the migration for the last change
Solution:
Drop tables involved in that migration of that app (consider a backup workaround if any)
Delete the rows responsible of the migration of that app from the table django_migrations in which migrations are recorded, This is how Django knows which migrations have been applied and which still need to be applied.
And here is how solve this problem:
log in as postgres user (my user is called posgres):
sudo -i -u postgres
Open an sql terminal and connect to your database:
psql -d database_name
List your table and spot the tables related to that app:
\dt
Drop them (consider drop order with relations):
DROP TABLE tablename ;
List migration record, you will see migrations applied classified like so:
id | app | name | applied
--+------+--------+---------+
SELECT * FROM django_migrations;
Delete rows of migrations of that app (you can delete by id or by app, with app don't forget 'quotes'):
DELETE FROM django_migrations WHERE app='yourapp';
log out and run your migrations merely (maybe run makemigrations in your case):
python manage.py migrate --settings=your.settings.module_if_any
Note: it is possible that in your case will not have to drop all the tables of that app and not all the migrations, just the ones of the models causing the problem.
I wish this can help.
Django migrations are recorded in your database under the 'django_migrations' table. This is how Django knows which migrations have been applied and which still need to be applied.
Have a look at django_migrations table in your DB. It may be that something went wrong when your migration was applied. So, delete the row in the table which has the migration file name that is related to that column that 'does not exist'. Then, try to re-run a migration.
Here's what i tried and it worked:
Go and add manually the column to your table
run python manage.py makemigrations
go back drop that column you added
run python manage.py migrate
I had a similar issue - the error message appeared when I clicked on the model on the django-admin site. I solved it by commenting out the field in models.py, then running migrations. Following this I uncommented the field and re ran the migrations. After that the error message disappeared.
My case might be a bit obscure, but if it helps someone, it is worth documenting here.
I was calling a function in one of my migrations, which imported a Model of said migration regularly, i.e.
from myApp.models import ModelX
The only way models should be imported in migrations would be using e.g. RunPython:
def myFunc(apps, schema_editor):
MyModel = apps.get_model('myApp 'MyModel')
and then calling that function like so:
class Migration(migrations.Migration):
operations = [
migrations.RunPython(initialize_mhs, reverse_code=migrations.RunPython.noop),
]
Additionally the original import worked until I modified the model in a later migration, making this error harder to locate.
So, I always run into this sort of problem, so today I decided to try and work it out at the database level. Thing is, I changed a model field name which Django didn't bother reflecting in a migration file. I only found out later when I ran into problems. I later looked at the migration files and discovered there was no migration for that change. But I didn't notice because I made other changes as well, so once I saw a migration file I was happy.
My advice. Create migration for each change one at a time. That way you get to see if it happened or not.
So here's my working through it in MySQL.
open mysql console.
show databases; # see all my dbs. I deleted a few
drop database <db-name>; # if needed
use <db-name>; # the database name for your django project
show tables; # see all tables in the database
DESCRIBE <table-name>; # shows columns in the database
SHOW COLUMNS FROM <db-name>; # same thing as above
ALTER TABLE <table-name> CHANGE <old-column-name> <new-column-name> <col-type>; # now I manually updated my column name
If you're using postgresql, just google the corresponding commands.
The issue was in the Models for me, for some reason Django was adding '_id' to the end of my Foreign Key column. I had to explicitly set the related named to the Foreign Key. Here 'Cards' is the parent table and 'Prices' is the child table.
class Cards(models.Model):
unique_id = models.CharField(primary_key=True, max_length=45)
name = models.CharField(max_length=225)
class Prices(models.Model):
unique_id = models.ForeignKey(Cards, models.DO_NOTHING)
Works after changing to:
class Cards(models.Model):
unique_id = models.CharField(primary_key=True, max_length=45)
name = models.CharField(max_length=225)
class Prices(models.Model):
unique_id = models.ForeignKey(Cards, models.DO_NOTHING, db_column='unique_id')
When I get this error, my extreme way to solve it is to reset my database:
Reset your database
For Postgresql on Heroku:
Heroku > your_app > Resources > database > add-ons > click on your database and open it
For postgresql
settings > Reset database
Delete all files in your_app > migrations > __pycache__ except __init.py__
Delete all files in your_app > migrations except __pycache__ folder and __init.py__
Then run:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
type in to create your superuser, then run:
python manage.py makemigrations
python manage.py migrate
python manage.py
If you are able to inspect your models from your admin section, then it should be all okay now.
Just remove corresponding row migrations for that model in 'django_migrations' model in database.
And re run python manage.py migrate app_name
I tried all these answers with not much luck! What I did to have this problem solved with no harm was to go back through the migration files and find where the actual model was being created for the first time then manually add the field (in the column not being existed error message). Until if you run makemigrations --dry-run you get/see "No changes detected" and that worked. Basically, in my case, I had to carefully take my desired db changes back in time in proper migration file, rather creating a new migration now at the end of migration dependency chain.
Open the latest py file created after running the makemigrations command inside migrations folder of that particular app.
Inside class Migration there is a list attribute called 'operations'.
Remove the particular elements migrations.RemoveField(...).
Save and run python manage.py migrate.
A easier solution to the problem is to make your models exactly like it is in the migration first. and run python manage.py migrate.
Then revert those changes
Run
python manage.py makemigrations
python manage.py migrate
To check for which migrations are applied and which are not, use -:
python manage.py showmigrations
I solved a similar problem by deleting all migrations files (Don't forget to make a backup) and python manage.py makemigrations all of them into one clean file in development and pulling new files on the server. Before then I had dropped existing tables on the PostgreSQL.
I was getting this error for some reason when Django was looking for a column of type ForeignKey named category_id when the actual name in the database was category. I tried every Django solution I could imagine (renaming field, explicitly setting column name, etc.). I didn't want to drop tables or rows as this was a production database. The solution was simply to rename the column manually using SQL. In my case:
ALTER TABLE table_name
RENAME COLUMN category TO category_id;
Make sure you backup your database, ensure this won't break any other applications consuming that particular table, and consider having a fallback column if necessary.
What helped me in the end was simply dropping the database and creating it again as well as deleting all migrations files (including cache). (only removing migrations file didn't work for me at all)
sudo su - postgres
psql
DROP DATABASE 'yourdatabase';
CREATE DATABASE 'yourdatabase';
GRANT ALL PRIVILEGES ON DATABASE 'yourdatabase' to 'yourdjangouser';
then just
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
If you're in development and you make some examples of data that's not important, this step is beneficial for me: just flush your data, make migrations, and migrate:
python manage.py flush
python manage.py makemigrations
python manage.py migrate
After that, you may create a new database from scratch, I hope this information was helpful.
Solved this issue by running
python manage.py migrate
in Heroku Bash shell
I need to change the name of the options in a model status field, which needs to become
STATUS = Choices(
('option_A', 'Option A'),
('option_B', 'Option B'),
)
Before this change, I had the same options but the names where different. Now I changed everything in the project to respect the new names, but the problem is about updating the database in order to display those new names. I use South for data migrations, and as far as I understand it is fairly straightforward to have it write an automatic migration if you need to add or delete a column in the database but I can't find a way to do this update to my existing column.
I use Django 1.6.
What you're looking for is a datamigration.
$ python manage.py datamigration your_app_label
This will create a new, blank migration in your migration folders. You have to manually create the forwards and backwards methods to change the data how you want it to be:
def forwards(self, orm):
orm.MyModel.objects.filter(status='old_option_A').update(status='option_A')
...
def backwards(self, orm):
# reverse of forwards, or raise an error to prevent backwards migrations
You'll need to use orm.MyModel instead of directly importing the model for this to work.
Then, simply run the migration:
$ python manage.py migrate your_app_label
Be sure to include both the migration and the change in your options in the same commit in your version control system, so these will always be synced (as long as people remember to migrate on a new version).
You could write a quick script to make your changes.Something like this:
>>Model.objects.filter(status = "some_old_value").update(status = "new_value")
Where 'status' is field name.
You can repeat the above step to change any kind of old values to new values in the same model.
Update() is much faster and shouldn't take long time to run on a moderately sized database
https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once
Also since it would be a one-time script, speed should not be a major issue.
Hope this helps
After you change your fields you should run:
$ python manage.py makemigrations your_app_label
$ python manage.py migrate
(This work for Django 1.7 where South are included into Django package)
In case of Django 1.6:
pip install South
-python manage.py schemamigration your_app_name --initial
-python manage.py migrate your_app_name
make change to your model
manage.py schemamigration your_app_name --auto (migration with your
changes will be added)
python manage.py migrate your_app_name
Also here are first steps tutorial for South Migration.
I have changed the Django models, and I use the Django schemamigration to update the database. But, when I do python manager.py migrate app, it throws this error message:
_mysql_exceptions.OperationalError: (1050, "Table 'forum_user' already exists")
Then the table that django south is trying to create already exists and doesn't match the state of your database.
If this is the first time you're migrating, remember that before you make schemamigration changes, you must set the initial state via schemamigration myapp --initial and migrate app --fake to match the database to the south database state.
manage.py convert_to_south myapp also does the above as a convenience method.
To start using south...
Make sure your django tables match your current database tables exactly - if you planned to add or remove columns, comment those out.
Run python manage.py schemamigration myapp --initial
Run python manage.py migrate myapp --fake
Make changes to your django model
Run python manage.py schemamigration myapp --auto
Run python manage.py migrate myapp
Update
Note django 1.7+ ships with migrations and south is no longer in use.
There are only two commands worth noting..
manage.py makemigrations (handles --initial)
manage.py migrate
Written by the same author as South, crowd funded. Go django.
I just fixed a duplicate table issue locally and wanted to document my workflow to help others.
The key to success was creating an --empty migration before the new models are added. The flow:
Merged in another persons work that excluded info on a model I have locally.
normal schemamigration --auto was adding a table/model again and caused "already exists error".
Solved by commenting out the new model and running an empty migration via clear; python manage.py schemamigration --empty APPNAME MIGRATION_FILE_NAME. This creates a "declaration" of the state of the models with no forward/backwards commands. Be 100% sure the current state of models (python files) and database are in sync!!! This most current migration will be used for the creation of a differential to migrate correctly (next).
uncomment the new model and run clear; python manage.py schemamigration APPNAME --auto to create the true and desired differential off (uses the --empty migration just created). The new migration will have forward/backward commands that should be appropriate for your new model. Review...
finish off with clear; python manage.py migrate
The lesson learned is that --auto looks at the last APP+migration file to create a forward/backwards diff. If the last migration does NOT have in the dictionary a model you have in DB it will be created again causing an "already exists" error. Think of the dictionary as a contract between Django and the DB stating "here's what everything should look like". The migration can include commands that create duplicate tables and will only be exposed during ```migrate`` command.
The above info should fix the problem. Presented in part to help people and also for review in case I am doing something foolish.
In Django how do you remove models that you have synced into the database?
For example in Django tutorial page had this following code
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Then I used python manage.py sql polls and python manage.py sql choice to create the tables into the database. But what if I did something wrong and don't want that model any more. What's the syntax to remove it?
If you don't want to delete and re-sync your current database, the best way is to drop the table from your model manually:
$ python manage.py dbshell
> (Inside the DB shell)
> DROP TABLE {app-name}_{model-name};
Why not simply try deleting the models from your models.py file? When you run
python manage.py makemigrations
the migrations file should be updated with the deleted models.
There is no syntax. Django doesn't removes tables or columns. You have to manually change your database or use a migration tool like South.
If you justing playing around with tutorial the easier way is to delete your sqlite database file and run a sync again.
Commenting out the class that defines the model did it for me. Once I had done it and ran python manage.py makemigrations,
I got this as response:
- Delete model MyModel.
Checked afterwards with a DB Browser and it was actually removed.
The most easiest solution is to just delete your model from models.py and run
python3 manage.py makemigrations
(Note: Remove the model from everywhere where you have imported it like admin.py, views.py, or any other file where you have imported it)
If you are facing issue to update changes onto DB so you can directly run this command.
python manage.py migrate --run-syncdb
I found a simpler method, by sheer experimentation. Even after deleting tables, Django was not making the migrations, so I did the following:
Simply delete the files created in your myapp->migrations directory, making sure that you do not delete the init.py and pycache
Starting from 001initial.py and downwards delete the files.
Run python manage.py makemigrations
Run python manage.py migrate
-M
Django’s database handling through syncdb is purely additive: any new models will be added, but deleted models will not be deleted and modified models will not be modified.
If you do not have any data you want to preserve, you are fine just dropping and recreating the database: if you have anything you want to preserve, or even if you intend to have anything you want to preserve, I cannot advise you strongly enough to use a migration tool: South has been the de facto standard for every project I’ve worked on.
Since the Migration command handle Model(database) you can do following steps.
First type
python manage.py makemigrations app_name # it will restructure your model
then type
python manage.py migrate app_name # it will apply to restructure your database.
Example:
I had Posts and PostDetail model,
later on, I wanted to remove PostDetail model and some fields(columns) from Posts model too.
I simply run migrations and migrate commands,checked in Mysql Database. It worked fine.
Hope it will work for you too.
Weather you’re removing a single model or a full app, you should first
remove the desired models from the models.py file.
Moreover, you have to make sure that no other file imports these
models or uses them (admin.py, views.py, etc).
Next, run South or migrate your database to properly delete these
models from your database.
Check the source of this information on the link below:
http://www.marinamele.com/how-to-correctly-remove-a-model-or-app-in-django
I am using Django with Postgres and Heroku. and I have a post table with looks something like this.
class Post( models.Model ):
.
.
content1 = models.CharField(max_length=1000)
.
One of my friends told me that limit is too small, now I want to change that maxlength to 10000. One way I can think of alternating the table by creating a new column named content2 then copying the content from content1, then deleting content1. I am fairly new to this and was wondering what was the best way to approach this problem.
Also is 10000 is a good length for a blog post? :D
You can either use dumpdata to save the data to a json-file and reload it after you re-create it, you can also manually ALTER the table with the new parameters. Or you can use south.
South provides databas migrations (as its called to change a table layout) for django.
pip install south
Add south to INSTALLED_APPS then run
python manage.py schemamigration --initial your_app_name
python manage.py migrate --fake your_app_name
Do your changes to the models.py, then run
python manage.py schemamigration --auto your_app_name
python manage.py migrate your_app_name
Now if you have the same database layout to change on several machines, check in the created migrations-files to git and run the "migrate" commands on all the machines that needs to update.