【发布时间】:2019-08-19 13:58:49
【问题描述】:
我的最后一次迁移是触发配置文件应用程序缩略图更新的数据迁移
def trigger_thumbnails_update(apps, schema_editor):
"""
Trigger thumbnails update for profile app
"""
User = apps.get_model('profile', 'User')
for user in User.objects.all():
if user.photo:
make_image_thumbnail.delay()
class Migration(migrations.Migration):
dependencies = [
('profile', '0008_auto_20190611_2120'),
]
operations = [
migrations.RunPython(trigger_thumbnails_update),
]
之后,我添加了一个名为is_daleted 的字段,然后运行makemigrations:
class Migration(migrations.Migration):
dependencies = [
('profile', '0009_trigger_thumbnails_update'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
效果很好,但是当我运行测试 (pytest) 时出现错误:django.db.utils.ProgrammingError: column profile_user.is_deleted does not exist
我认为这是由于我的数据迁移在导入时触发了查询,因此它在迁移之前运行。
评论触发代码暂时解决问题,我需要一个真正的解决方案,请
更新这里是完整的回溯:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: column profile_user.is_deleted does not exist
LINE 1: ...r"."is_onboarded", "profile_user"."last_request", "profile_u...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 385, in trace_task
R = retval = fun(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 648, in __protected_call__
return self.run(*args, **kwargs)
File "/opt/app/apps/utils/tasks.py", line 18, in make_image_thumbnail
obj = Model.objects.get(pk=pk)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 393, in get
num = len(clone)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __len__
self._fetch_all()
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1183, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 54, in __iter__
results = comp...
【问题讨论】:
-
它将在第二个查询之前运行查询,因为您将其定义为依赖项。
-
函数
make_image_thumbnail从何而来?由于历史模型的问题,您应该尽量不要从模型文件中导入函数。进行数据迁移时,将函数代码复制到数据迁移代码中(即使复制代码),这样以后更改函数时就不会出现问题。迁移代码需要是“静态的”,即在应用迁移后永远不会更改。 -
请发布完整的回溯。但很可能这个问题正是 dirkgroten 所解释的问题。
标签: django django-models django-migrations