如何在具有继承模型的 Django 迁移中使用默认管理器?

How to use default manager in django migrations with inherited models?

我有一个模型 Baz 继承自抽象模型 Bar,它也继承自另一个抽象模型 Foo

from django.db import models


class BarManager(models.Manager):
    pass


class Foo(models.Model):
    attr1 = models.CharField(max_length=20)

    objects = models.Manager()

    class Meta:
        abstract = True


class Bar(Foo):
    attr2 = models.CharField(max_length=20)
    bar_objects = BarManager()

    class Meta:
        abstract = True


class Baz(Bar):
    attr3 = models.CharField(max_length=20)

当运行进行数据迁移时我希望能够使用默认管理器Baz.objects:

# Generated by Django 3.0.7 on 2020-06-23 15:57

from django.db import migrations


def update_forward(apps, schema_editor):
    Baz = apps.get_model('migration_manager', 'Baz')
    Baz.objects.filter(attr1='bar').update(attr1='baz')


class Migration(migrations.Migration):

    dependencies = [
        ('migration_manager', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(update_forward),
    ]

但它不可用,因为我得到:

  File "/home/user/code/django_issues/migration_manager/migrations/0002_update_content.py", line 8, in update_forward
    Baz.objects.filter(attr1='bar').update(attr1='baz')
AttributeError: type object 'Baz' has no attribute 'objects'

这是自动创建的初始迁移

# Generated by Django 3.0.7 on 2020-06-23 16:13

from django.db import migrations, models
import django.db.models.manager


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Baz',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('attr1', models.CharField(max_length=20)),
                ('attr2', models.CharField(max_length=20)),
                ('attr3', models.CharField(max_length=20)),
            ],
            options={
                'abstract': False,
            },
            managers=[
                ('bar_objects', django.db.models.manager.Manager()),
            ],
        ),
    ]

其中 managers 部分明确仅提供父项的自定义模型。

有谁知道是我做错了什么还是 django 有问题?

我在:

提前致谢

使用Model._default_manager作为

Baz<b>._default_manager</b>

完整示例:

def update_forward(apps, schema_editor):
    Baz = apps.get_model('migration_manager', 'Baz')
    Baz._default_manager.filter(attr1='bar').update(attr1='baz')