django - Django MPTT:在迁移文件中重建树
问题描述
我的项目中已经有一个模型,现在我想与 django-mptt 一起使用。该模型中已经包含一些数据。
在迁移期间,系统会要求您为 django-mptt 创建的某些字段设置默认值。按照文档中的指示,我将 0 设置为一次性默认值。文档继续进行并建议Model.objects.rebuild()
在完成此操作后运行以在字段中设置正确的值。我想通过我的迁移文件执行此操作。我不想通过我的 django-shell 运行它,因为这不是一次性操作。
我的迁移文件是这样的:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-12-27 17:33
from __future__ import unicode_literals
from django.db import migrations, models
def migrate_mptt(apps, schema_editor):
ProductCategory = apps.get_model("product", "ProductCategory")
ProductCategory.objects.rebuild()
class Migration(migrations.Migration):
dependencies = [
('product', '0016_auto_20181227_2303'),
]
operations = [
migrations.RunPython(migrate_mptt),
]
在迁移时,我收到错误AttributeError: 'Manager' object has no attribute 'rebuild'
。当然,相同的命令在 shell 中也能完美运行。
我需要通过迁移来做到这一点,因为我希望每次部署我的项目时自动运行此操作。
解决方案
如果您想重建适当的迁移,您可以使用此代码。如果您AttributeError
对此有所了解,请尝试将模型管理器设置为your_name
属性(而不是objects
)。
此外,如果您希望在迁移后重建,您可以扩展您的应用配置:
from django.apps import AppConfig
from django.db.models.signals import post_migrate
def rebuild_tree(sender, **kwargs):
from .models import YourModel
YourModel.objects.rebuild()
class YouApponfig(AppConfig):
name = 'app_name'
def ready(self):
post_migrate.connect(rebuild_tree, sender=self)
推荐阅读
- python - Tkinter 模块 - 程序将运行然后停止并且不会打开窗口
- java - JUnit 5 中的系统属性和并行测试执行
- javascript - 毫不拖延,“更新”不会触发
- vba - 循环遍历用户窗体上的控件以隐藏特定控件
- linux - 在 Linux Mint 18.2 上为 Yiynova 平板电脑安装内核驱动程序时遇到问题
- laravel - Laravel 5.7 - 检查是否不等于 id 或 null 且不等于另一个 id 和 team_id 不在 (?, ?) 中的 Eloquent 查询
- c# - 无需委派 VBA/C# 即可获取 Outlook 共享日历
- regex - 正则表达式两个首字母
- c# - 将多个自定义标记添加到 Bing 地图 (API) 示例
- java - 杰克逊:反序列化地图
自定义嵌套 Pojo