您好,这主要是Google小组中提出的问题的副本:
感谢Wagtail文档,我能够理解如何构建自定义图像模型,但是,因为我有一个包含500多个内容的网站,我不想因为数据迁移不好而搞得一团糟。 实际上,我不确定我应该在这里使用哪种迁移操作。 我想我应该这样:documentation 有人能证实吗?
非常感谢 问候
编辑:提供有关迁移的一些细节
这肯定是特定的,为什么我可能省略了一些细节。对不起。由于我没有太多的声誉,我不能提供超过2个链接的单个帖子
答案 0 :(得分:3)
我最近也进行了同样的迁移到我自己的定制模型,但是,我们没有积极使用标签,所以我不担心转移标签。此迁移不会删除原始的Image数据库记录,因为我希望保留它们以防万一。
第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
如下编辑该文件(请参阅内联评论)
```
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