首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django MPTT:在迁移文件中重建树

Django MPTT:在迁移文件中重建树
EN

Stack Overflow用户
提问于 2018-12-28 02:40:48
回答 1查看 535关注 0票数 1

我在我的项目中已经有了一个模型,现在我想和django-mptt一起使用。此模型中已包含一些数据。

在迁移过程中,系统会要求您为django-mptt创建的一些字段设置默认值。按照文档中的指示,我将0设置为一次性默认值。文档将继续,并建议在完成此操作后运行Model.objects.rebuild(),以便在字段中设置正确的值。我想通过我的迁移文件执行此操作。我不想通过我的django-shell运行它,因为这不是一次性的操作。

我的迁移文件是这样的:

代码语言:javascript
复制
# -*- 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中也能完美地工作。

我需要通过迁移来做到这一点,因为我希望在每次部署我的项目时自动运行此操作。

EN

回答 1

Stack Overflow用户

发布于 2019-05-23 20:58:45

如果你想在迁移时进行重建,你可以使用to use this code。如果您用它捕获AttributeError,请尝试将模型管理器设置为your_name属性(而不是objects)。

此外,如果您希望在迁移后重新构建,您可以扩展您的应用程序配置:

代码语言:javascript
复制
    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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53949475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档