python - 如何使用迁移来移动数据

标签 python django python-3.x django-models

我有一个场景,我需要将数据从一个模型(一些数据已存在的旧模型)移动到另一个模型,并在必要时再移动到另一个模型。我如何添加这个在迁移文件中进行处理,以便我只需使用 python manage.py migrate 命令即可完成要求。

这是所有旧项目都存在的模型:

class UserFavorite(CreatedAtMixin):
    user = models.ForeignKey('auth.User')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

objects = UserFavoriteManager()

def __str__(self):
    try:
        return str(self.content_object)
    except AttributeError:
        return 'None'

class Meta:
    get_latest_by = "date_added"
    unique_together = ("user", "content_type", "object_id")`

这是我需要首先插入项目的模型,上面模型中的每个项目:

class CollectionItem(models.Model):

sort_number=models.PositiveIntegerField(blank=True,null=True)
type=models.CharField(max_length=20,null=False, blank=False)
item_type = models.ForeignKey(ContentType, limit_choices_to=models.Q(app_label='news', model='News') | models.Q(app_label='work', model='Work') | models.Q(app_label='collection', model='Quote'))
item_id = models.PositiveIntegerField()
item = generic.GenericForeignKey('item_type', 'item_id')

class Meta:
    verbose_name = "Collection Item"
    verbose_name_plural = "Collection Items"
def __str__(self):
    return self.item.title

然后我需要将其插入:

class Collections(CreatedAtMixin):
user = models.ForeignKey('auth.User', related_name='collections_user')
collection_place=models.ForeignKey('companies.CompanyOffice',related_name='collections_place',null=True)
collection_name = models.CharField(max_length=40,null=False, blank=False)
description = models.TextField(null=True, blank=True)
items=models.ManyToManyField('collection.CollectionItem')
def __str__(self):
    return self.collection_name

class Meta:
    unique_together = ("user","collection_name")
    verbose_name = "Collection"
    verbose_name_plural = "Collections"
    ordering = [ '-created_at']
    get_latest_by = "created_at"

最佳答案

首先编写您的新模型和 create a schema migration

然后create a data migration并编写所需的代码以将旧模型数据传输到新模型(提示:如果可能,还可以编写代码来恢复迁移)。

最后 - 假设不再使用旧模型 - 删除旧模型代码并创建最后一个架构迁移。

详细信息均记录在上述链接中,剩下的内容特定于您的应用程序,因此我们无法提供进一步帮助。

关于python - 如何使用迁移来移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44652417/

相关文章:

python - 在python中检测程序

python - 删除 Django 模板中的引号

python - 我不知道我的数据库名称

python - 如何获取 Pandas DataFrame 中 2 个列表的差异?

python - 使用 python requests 库将文件发布到服务器时出现错误请求错误

python - 如何将 FastAPI UploadFile(zip 文件)以 .zip 格式保存到磁盘?

python - 如果所有行都包含至少一个负元素,则更改矩阵中元素的符号

python - os.startfile错误: FileNotFoundError: [WinError 2] The system cannot find the file specified:

python - 隔离依赖于初始化程序的测试的好方法

django - 为什么使用 django TemplateTag 标签?