我最近做了同样的迁移到我自己的定制模型,但是,我们没有积极使用标签,所以我不担心跨标签转移。此迁移不会删除原始图像数据库记录,因为我想保留它们以防万一。
第 1 步 - 创建模型
app_name/models.py
from django.db import models
from wagtail.wagtailimages.models import (
Image, AbstractImage, AbstractRendition)
class ExtendedImage(AbstractImage):
caption = models.CharField(max_length=255, blank=True)
admin_form_fields = Image.admin_form_fields + (
'caption',
)
class ExtendedRendition(AbstractRendition):
image = models.ForeignKey(ExtendedImage, related_name='renditions')
class Meta:
unique_together = (
('image', 'filter_spec', 'focal_point_key'),
)
第 2 步 - 运行迁移
看起来你可能已经这样做了,它会创建自定义模型
- $
python manage.py makemigrations
- $
python manage.py migrate
第 3 步 - 创建自定义数据迁移
$python manage.py makemigrations --empty app_name
如下编辑该文件(参见 cmets inline)
```
from __future__ import unicode_literals
from django.db import migrations
# This only COPIES images from the existing model to the new one
# to reverse during testing - run
# ./manage.py migrate main 0036_auto_20170524_1811 (replace with file name of previous migration)
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
wagtail_image_model = apps.get_model('wagtailimages', 'Image')
extended_image_model = apps.get_model('main', 'ExtendedImage')
db_alias = schema_editor.connection.alias
# Get images
images = wagtail_image_model.objects.using(db_alias).all()
new_images = []
for image in images:
new_images.append(extended_image_model(
id=image.id,
title=image.title,
file=image.file,
width=image.width,
height=image.height,
created_at=image.created_at,
focal_point_x=image.focal_point_x,
focal_point_y=image.focal_point_y,
focal_point_width=image.focal_point_width,
focal_point_height=image.focal_point_height,
file_size=image.file_size,
# image=test_image.caption,
collection=image.collection,
# tags=image.tags, # does not copy over
uploaded_by_user=image.uploaded_by_user,
))
# Create images in new model
extended_image_model.objects.using(db_alias).bulk_create(new_images)
# Leave all images in previous model
def reverse_func(apps, schema_editor):
# We get the model from the versioned app registry;
extended_image_model = apps.get_model('main', 'ExtendedImage')
db_alias = schema_editor.connection.alias
# Delete all images created in the new model
extended_image_model.objects.using(db_alias).all().delete()
class Migration(migrations.Migration):
dependencies = [
('main', '0036_auto_20170524_1811'), # Django will create this part
]
operations = [
migrations.RunPython(forwards_func, reverse_func),
]
```
第 4 步 - 更新设置
WAGTAILIMAGES_IMAGE_MODEL = 'my_app.ExtendedImage'
在此过程中进行测试,准备好后,您可以根据需要删除原始图像数据库行。
** 关于 Postgres 的注意事项
我们遇到的一个问题是 Postgres 不喜欢我将东西迁移到主键,我们必须运行 SQL 查询来将当前键重置为 max + 1