前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django migrate 常见错误总结 and 对应方法

django migrate 常见错误总结 and 对应方法

原创
作者头像
刀枪不入de王二花
发布2022-08-26 13:18:35
1.6K0
发布2022-08-26 13:18:35
举报
文章被收录于专栏:BETTERBETTER

操作:

python manage.py makemigrations <appname>

python manage.py migrate <appname>

说明:

本文列举了

1~4具体的常见问题(error log),和

5,migrate差分移行错误的解决办法。

若解决方案都不满足,就按照5阐述的方法,自己调查一下吧,答案都在log里~(每天进步一点点,我离大神就不远)

常见问题:

1,You are trying to add the field 'created_at'with'auto_now_add=True' to xxx without a default;

原因:auto_now_add字段需要设定初期值

解决:按照提示,选择1 后,

  输入【timezone.now()】,now 带括号,( 直接敲enter也可,默认设定timezone.now)

  或者自己输入一个时间,例:datetime.datetime(2022,8,26,13,20)

代码语言:javascript
复制
You are trying to add the field 'created_at' with 'auto_now_add=True' to receive without a default; the database needs something to populate existing rows.

 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: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>> timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>> timezone.now()

2,django.db.utils.ProgrammingError: relation "jobs_h1_table" already exists

  django.db.utils.ProgrammingError: リレーション"jobs_h1_table"はすでに存在します。

問題原因:DB中的表没删干净

解决:方法①drop table <error table> 后,重新执行migrate

   方法②python manage.py migrate <appname> --fake-initial 参照fake initial

注意:想把某个app下的表全部重新作成,需要按步骤:(a,b,c无顺序要求)

a,drop table <app tables>

b,对象app > migrations folder 删掉

c,DB:django_migrations 表中,对应app的信息删除

d,python manage.py makemigrations <appname>

e,python manage.py migrate <appname>

3,django.db.utils.ProgrammingError: relation "jobs_h1_table" not exists

类似错误信息:

  psycopg2.errors.undefinedtable relation does not exist

  django.db.utils.ProgrammingError: リレーション"jobs_h1_table"は存在しません

  django.db.utils.ProgrammingError: リレーション"jobs_h1_table"の列"detail_id"は存在しません

  ※若是新作成的model报table不存在,若是既存的model变更追加了字段,则报field不存在

問題:table/ column存在しないエラー

操作:python manage.py makemigrations app1

   ※jobs_h1_table 在 App2 里定义,与app1无关

前提:app2,app1 中的model无参照关系 (例:App2中model的外键指向 app1的model)

   ※若存在参照关系,那按照 parent→chilren的顺序,执行移行即可解决。

原因:INSTALLED_APPS 装了【django_db_comments】

   django_db_comments 遍历所有model,并对应给DB table加上注释

   若有App1,App2,App3,移行时没有全体对象作成而是个别app指定,

   未移行的model,就会报找不到table的错误

解决

1,该错误并不影响移行本身,确认数据库,对应app下的表都被作成的话,可以无视。

2,解决方案:

 ①根据原因,把对应app的移行文件一并生成(python manage.py makemigrations App2),再执行migrate

 ②settings.py INSTALLED_APPS ,先把app2 注释掉,移行完app1后再将注释打开

我的log参考:很明确,执行【django_db_comments】时出了错

代码语言:javascript
复制
 File "D:\PycharmProjects\smsenv\lib\site-packages\django_db_comments\db_comments.py", line 114, in copy_help_texts_to_database
    add_column_comments_to_database(columns_comments, using)
  File "D:\PycharmProjects\smsenv\lib\site-packages\django_db_comments\db_comments.py", line 57, in add_column_comments_to_database
    cursor.execute(query, [comment])
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\PycharmProjects\smsenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: リレーション"jobs_h1_receive"は存在しません

4,django.db.migrations.state.InvalidBasesError: Cannot resolve bases for

代码:

代码语言:javascript
复制
pj>app2>detail.py

from app1.models import Parent
class ChildrenInfo(Parent):                  #直接继承其他app下的model
    class Meta:
        verbose_name = 'children info'
        db_table = 'children_info'

error log:

代码语言:javascript
复制
django.db.migrations.state.InvalidBasesError: Cannot resolve bases for [<ModelState: 'jobs.modelname'>]
This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth)
in an app with no migrations; see https://docs.djangoproject.com/en/%s/topics/migrations/#dependencies
for more

log很明确,继承了其他app下的model,导致错误。

根据log的提示,看一下官网文档说了什么 dependencies

大概就是有依赖关系的app,要先migrate parent,再migrate childrens

While migrations are per-app, the tables and relationships implied by your models are too complex to be created for one app at a time. When you make a migration that requires something else to run - for example, you add a ForeignKey in your books app to your authors app - the resulting migration will contain a dependency on a migration in authors.This means that when you run the migrations, the authors migration runs first and creates the table the ForeignKey references, and then the migration that makes the ForeignKey column runs afterwards and creates the constraint. If this didn’t happen, the migration would try to create the ForeignKey column without the table it’s referencing existing and your database would throw an error.This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in makemigrations or migrate) is a best-efforts promise, and not a guarantee; any other apps that need to be used to get dependencies correct will be. Apps without migrations must not have relations (ForeignKey, ManyToManyField, etc.) to apps with migrations. Sometimes it may work, but it’s not supported.

解决:

1,首先必须判定,业务是否真的需要这样继承其他model,若只是参照parent model 的内容,定义成外键即可

代码语言:javascript
复制
pj>app2>detail.py
from app1.models import Parent
from django.db import models

修正前:
class ChildrenInfo(Parent):                  #直接继承其他app下的model
    class Meta:
        verbose_name = 'children info'
        db_table = 'children_info'

修正后:
class ChildrenInfo(models.Model):             #parent作为 FK
    parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, verbose_name='親', null=True)
    class Meta:
        verbose_name = 'children info'
        db_table = 'children_info'

2,若判定确实需要这样继承,migrate时,可将children app 从【INSTALLED_APPS】中注释掉,先移行parent,之后再将注释打开,移行children app

※也可添加【MIGRATION_MODULES】指定要迁移的对象app 参照

代码语言:python
代码运行次数:0
复制
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_db_comments',
    'django.contrib.humanize',
    'parent',
    # 'children_1',    # 将子app先注释掉,执行完migrate后,打开注释,再执行一次migrate
    # 'children_2',
]

5,其他field移行出错,差分移行常见

问题:移行内容很多,报错只有移行失败,或给出 出错位置, field名等信息

   比如:字段从null可→null不可,char→datetime

      因为数据库表里有数据,导致某列不能正确差分修改

调查方法:将log打开,再执行migrate,这样能看到,移行出错的位置,可定位到field log output 设定参考

对策

打开移行文件,找到对应字段,将update处理(alter),改为 delete+insert(remove+add)

重新migrate即可,这样整张表的数据就得以保存。

代码语言:javascript
复制
app1>migrations>0014_auto_20220826_1021.py

修正前:
      migrations.AlterField(
            model_name='sp',
            name='bank_account',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='master.bankaccount', verbose_name='銀行口座'),

修正后:
      migrations.RemoveField(
            model_name='sp',
            name='bank_account',
        ),
        migrations.AddField(
            model_name='sp',
            name='bank_account',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='master.bankaccount', verbose_name='銀行口座'),
        ),

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 操作:
  • 说明:
  • 常见问题:
    • 1,You are trying to add the field 'created_at'with'auto_now_add=True' to xxx without a default;
      • 2,django.db.utils.ProgrammingError: relation "jobs_h1_table" already exists
        • 3,django.db.utils.ProgrammingError: relation "jobs_h1_table" not exists
          • 4,django.db.migrations.state.InvalidBasesError: Cannot resolve bases for
            • 5,其他field移行出错,差分移行常见
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档