Reputation: 77
I have a model Baz
that's inheriting from an abstract model Bar
which is inheriting as well from an other abstract model 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)
when running a data migration I want to be able to use the default manager 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),
]
but it's not available as I'm getting:
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'
This is the initial migration that gets created automatically
# 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()),
],
),
]
in there there is the managers
section which is explicitly making available only the custom model of the parent.
Does anyone have an idea if it's me doing something wrong or it's an issue with django?
I'm on:
Thanks in advance
Upvotes: 0
Views: 689
Reputation: 88499
Use Model._default_manager
as
Baz._default_manager
Full example:
def update_forward(apps, schema_editor):
Baz = apps.get_model('migration_manager', 'Baz')
Baz._default_manager.filter(attr1='bar').update(attr1='baz')
Upvotes: 1