Django Migration Error: Column does not exist

后端 未结 15 2228
北恋
北恋 2020-12-10 10:25

Python 3, Django 1.8.5, Postgres

I have a model Sites that has been working fine. I recently tried to add a field, airport_code, and migrate the data.

相关标签:
15条回答
  • 2020-12-10 10:53

    Just now had the same error when I tried to migrate a SingletonModel to actually contain the necessary fields.

    Reason for the error was that my Model A used some fields of this SingletonModel (as configurable values). And during instantation of model A during the migration process it obviously couldn't guarantee that my migration was safe.

    A colleague had a wonderful idea. Make the default value for the field a function call, and therefor lazy.

    Example:

    class A (models.Model):
        default_value = models.DecimalField(default: lambda: SingletonModel.get_solo().value, ...)
    

    So therefor, my advice: Try and make the offending call (seen in stacktrace) a lazy one.

    0 讨论(0)
  • 2020-12-10 11:06

    Make sure you are not doing any queries when loading the application!, as eg. in:

    class A:
      field = fn_that_makes_query()
    

    When running migrate or makemigrations, Django performs system checks, which loads the entire application, so if during this process any queries are made which use added/altered db fields you run into inconsitencies, because you are trying to access db fileds that are not there yet.

    0 讨论(0)
  • 2020-12-10 11:07

    In my case it happens because of my custom AdminSite has MyModel.objects.filter on application start, i have disabled it for makemigrations and migrate database.

    0 讨论(0)
  • 2020-12-10 11:10

    I got the same issue, here is my case: in the app MyApp I add a new field to the model:

    class Advisors(models.Model):
        AdvID = models.IntegerField(primary_key=True)
        Name = models.CharField(max_length=200,null=False)
        ParentID = models.IntegerField(null=True) # <--- the NEW field I add
    

    so what I did is: in the urls.py of MyProject, NOT MyApp, comment out the url() linked to MyApp and then do makemigrations and migrate everything goes well; in MyApp/urls.py file:

    urlpatterns = [
        url(r'^admin/', admin.site.urls, name='admin'),
        url(r'^$', views.HomePage.as_view(),name='home'),
        #comment out the following line, after migrate success, bring it back;
        # url(r'^myapp/', include('myapp.urls',namespace='research')), <--- 
    ]
    
    0 讨论(0)
  • 2020-12-10 11:11

    Run into this problem after the migration of my postgres database to a differnt server. Somehow I messed up the database and could not update my model with the new class UserProfile.

    I solved the problem creating initial migration for existing schema:

    1. Empty the django_migrations table: delete from django_migrations;with a command DELETE FROM django_migrations WHERE app='my_app';
    2. For every app, delete its migrations folder: rm -rf <app>/migrations/
    3. Reset the migrations for the "built-in" apps: python manage.py migrate --fake
    4. For each app run: python manage.py makemigrations <app>. Take care of dependencies (models with ForeignKey's should run after their parent model).
    5. Finally: python manage.py migrate --fake-initial

    Got it here: https://stackoverflow.com/a/29898483

    PS I'm not sure that this was relevant to the resolution of the problem but, first, I dropped the table in postgresql that caused an error and commented out the UserProfile class in models.

    in shell:

     sudo -su postgres
     psql databse_name   
     DROP TABLE table_name;
    

    models.py:

    #class UserProfile(models.Model):
        #user = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True, primary_key=True, on_delete=models.CASCADE, related_name='user_profile')
        #avatar = ThumbnailerImageField(upload_to='profile_images', blank=True)
        #country = models.CharField(max_length = 128)
    
    0 讨论(0)
  • 2020-12-10 11:12

    I got the same problem (column not exist) but when I try to run migrate not with makemigrations

    • 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:

      1. Drop tables involved in that migration of that app (consider a backup workaround if any)
      2. 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='your_app';

    • 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.

    0 讨论(0)
提交回复
热议问题