No model tables are created for a Django migration - python

I have searched other articles (like this one) for a solution, but nothing has helped so far...
I realized while working on my project that I needed to alter the model, changing a primary key to an AutoField rather than use a custom field. I knew this would cause a lot of issues since I have quite a few ForeignKey fields, so I wanted to drop all of my tables, clear out the migrations, and just let the migrations re-generate all of the the tables. The problem is that even though I dropped all of the tables (and eventually the whole database, due to the django_migrations table and any other latent data), cleared out all of the project/app/migrations directories, when I run manage.py makemigrations/manage.py migrate, it only creates the built-in tables (the auth_* and django_* tables) and none of my model tables get recreated.
Where else do I need to clean up in order to be able to start over with a fresh database model? I thought that clearing out the migrations directories would be sufficient, but there's something else I'm missing.
Thanks.

If you have deleted the migrations folder for an app, you have to specify the app name to create the initial migrations:
./manage.py makemigrations myapp

Related

ProgrammingError while opening admin table

I am using django with postgres database.
When loading the admin,clicking on Course Table, I get a classic error:
ProgrammingError at /admin/user_profile/course/
relation "user_profile_course" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "user_profile_course"
I tried makemigrations, and migrate it again but no success.
Would you please help me how to handle it?
My models.py looks like:
class Course(models.Model):
name=models.CharField(max_length=30)
number_of_sessions=models.IntegerField()
student=models.ManyToManyField(User, through='Registration')
Edit:
I removed the migration folder, and make migrations again.
in the 0001initial.py the dependencies looks like:
dependencies = [
('auth', '0007_alter_validators_add_error_messages'),
]
It looks like you've removed already applied migration from your migrations folder and re-created it with different model state (with extra model Course).
That will create situation when actual structure of your database is different than state that should be after applying your migration.
Now you can either fix your migration or fix your database structure.
To accomplish first possible fix, you need to check your current state of database and compare it with your migration file. If there is something different in your migration file, simply change it to reflect your database structure.
If you don't know how to edit migration file, you can change your models to reflect database structure, remove your migration and then create it again using makemigrations.
After fixing your migration file, generate second one, just running makemigrations with having desired models structure in your models files.
For second solution, check what's inside your migration file and edit your database structure to reflect that.
And remember, do not ever delete or change already applied migration, unless you really know what you're doing!

Django Rebuild all migrations

I am building an app in Django and it uses a live/in-use database.
Basically since the apps development the SQL Database has undergone some structure changes and it is causing issues with Django, Django will try to apply migrations to the database that already exist. For example:
In the Django app I marked the email column as unique which was fine based on the development database. However the main database now always has a table change that marks the email column as unique. Django is fighting this unique key with the one that already exists.
So is it possible to clear all Django migrations and have it make migrations again compared to the more up to date SQL database structure?
If your models are very out of sync with your database, the easiest option is probably to rebuild your models from scratch using inspectdb.
If your models are pretty close to the database already, the first step is to make sure that your models match the database exactly. You can use sqldiff from django-extensions for this.
Once your Django models match your database, follow this answer to re-create migrations based on the existing database schema.

Django: Quickly deal with adding non-nullable field

When developing models I quite often get the non-nullable field error when running makemigrations:
You are trying to add a non-nullable field 'user' to randommodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
Almost all the time when I get this error I'm quite happy to delete the data in that table (it's normally only a couple of test entries while developing) and it would be more efficient to just delete it rather than determine what a suitable default would be.
However currently I don't have a suitable method for doing this and end up flushing the database and/or deleting the migrations, which is pretty heavy handed but works.
What's the best way to delete the data just in that model/table to remove the error? (Would it be via shell/shell_plus?)
Model:
class RandomModel(models.Model):
user_details = JSONField(unique=True)
user = models.ForeignKey(User)
Even if you have deleted all the records in that table, when running makemigrations, you'll be asked to provide default values again. This is because you're making a new migration file for an existing table.
One solution I can think of is to tell Django that you're starting that app_name over again by running migrate app_name zero. This will unapply all migration files that have ever been applied to your database.
Then delete all the migration files in your app_name. And run makemigrations again. This would create a new initial migration file. Then you just apply it to your database with migrate.
As you've said you don't mind deleting your data. This is even better. You don't have to even delete any record. It will just create a new table with the same name with all the new fields and with 0 record.

Django 1.7.1 requires a Default value for field - but no entry is in database. Why?

I ran into a strange problem. I'm using Django 1.7.1 on Mac OS X Yosemite and I have configured a local MySQL database.
Normally, I create a model and if I want to add another field, I just do a ./manage.py migrate and Django creates a new database column.
I did exactly that. Here's my model:
from django.db import models
from django.utils.translation import ugettext as _
class Product(models.Model):
CATEGORY_CHOICES = (
('apphosting', _('Application Hosting')),
('webhosting', _('Web Hosting'))
)
category = models.CharField(max_length=25, choices=CATEGORY_CHOICES)
name = models.CharField(max_length=25)
price_monthly = models.FloatField()
def __unicode__(self):
return self.name
Please note that I have added the field price_monthly. Then, I did a ./manage.py migrate:
(mysphere)dmanser#ragamuffin:~/git/mysphere on master [!?]$ ./manage.py migrate
Operations to perform:
Synchronize unmigrated apps: crispy_forms
Apply all migrations: customers, sessions, admin, sites, flatpages, contenttypes, products, auth
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
So ok, I do a ./manage.py makemigrations, which results in:
(mysphere)dmanser#ragamuffin:~/git/mysphere on master [!?]$ ./manage.py makemigrations
You are trying to add a non-nullable field 'price_monthly' to product without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
The strange thing here is, that this model has no entry yet. So why should I need to provide a default value if there's no product in the database?
I'm starting to pull my hair out and I have tried several things yesterday. After 3 hours, I gave up.
The migrations system is designed so that a single migration can be applied to more than one database. For example, you could have a development version, a staging version, and one or more production versions. That's why making the migration is a distinct step from applying the migration, and why makemgirations can't just look at the currently active database to see that it doesn't have any rows. What if you then try to apply the migration to a database that does?
The solution in your case is simple: since there are no rows, option 1 (setting a default on all existing rows) won't do anything at all. So choose option 1, and any value you like.
You have already applied migrations before, so the table has already been created. Now you are adding a column that cannot be null, but have not defined a default value.
Since migrations will add a column to an existing table, it needs enough data so that your migration does not violate the schema; hence the prompt.
If you were to delete the table, and then run the migration you would not face this error. However as the initial migration has already created the table, any future migrations cannot not violate its referential integrity.
I have come across this many times, suppose you have app called app1 inside your project myproject, best thing you can do in this situation is to go and delete app1/migrations then try again it should work fine

What migration order does South follow across different apps?

I've recently begun using South for migrations in my Django project. All was going well until recently when I ran into a peculiar issue.
I have two apps in my project, say, App-A and App-B. A model in App-A has a foreign key to a model in App-B. When I've been trying to build my system, I ran syndb which created all the auth_ and the south_ tables. Then I ran migrate which threw up errors. When it tried creating the model from App-A, which referenced a model from App-B, the model App-B wasn't migrated/created as yet and therefore the error.
In order to resolve this, I had to manually migrate App-B first and then App-A. Am i doing something wrong here? How is South supposed to know the migration order across apps?
Thanks.
This explained it https://south.readthedocs.io/en/latest/dependencies.html.
Migrations for apps are nice ‘n all, but when you start writing a
large project, with a lot of apps, you realise you have foreign key
relationships between apps and working out what order migrations would
need to be applied in for each app is just painful.
Luckily, we also had this problem, so South has a dependency system.
Inside a migration, you can declare that it depends on having another
app having run a certain migration first; for example, if my app
“forum” depends on the “accounts” app having created its user profile
table, we can do:
# forum/migrations/0002_post.py class Migration:
depends_on = (
("accounts", "0003_add_user_profile"),
)
def forwards(self):
Then, if you try and migrate to or beyond 0002_post in the forum app, it will first make sure accounts is migrated at least
up to 0003_add_user_profile, and if not will migrate it for you.
Dependencies also work in reverse; South knows not to undo that
0003_add_user_profile migration until it has undone the 0002_post
migration.
You can have multiple dependencies, and all sorts of wacky structures;
there are, however, two rules:
No circular dependencies (two or more migrations depending on each
other) No upwards dependencies in the same app (so you can’t make
0002_post in the forum app depend on 0003_room in the same app, either
directly or through a dependency chain.
South migrates apps in the order they appear in the INSTALLED_APPS tuple in settings.py. So just make sure App-B comes before App-A in your settings.py, and it should work :)

Categories

Resources