我在我的项目中已经有了一个模型,现在我想和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中也能完美地工作。
我需要通过迁移来做到这一点,因为我希望在每次部署我的项目时自动运行此操作。
发布于 2019-05-23 20:58:45
如果你想在迁移时进行重建,你可以使用to use this code。如果您用它捕获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)https://stackoverflow.com/questions/53949475
复制相似问题