I'm trying to create a datamigration using update queryset method. I have a complex migration process for my case, so i faced the following problem. The simple example
from __future__ import unicode_literals
from django.db import migrations, models
def move_data(apps, schema_editor):
MyModel = apps.get_model("my_app", 'MyModel')
MyModel.objects.all().update(new_field=models.F('old_field'))
class Migration(migrations.Migration):
dependencies = [
('orders', '0057_auto_20170410_1513'),
]
operations = [
migrations.RunPython(move_data),
]
In my case i got FieldError. F() object can't resolve the field old_field, but if i will use something like this
for obj in MyModel.objects.all():
obj.new_field=obj.old_field
obj.save()
instead of
MyModel.objects.all().update(new_field=models.F('old_field'))
all will be good
I have a few models inherited from one base model and i need to move some fields from on of the child model to parent. So i made this with the following steps
I faced this at the 3 step and can't understand why it don't works
Can somebody provide some explanation of this?
Is it related to the model state rendering process somehow?
UPD. The simplified definition of models
class Base(models.Model):
pass
class MyModel1(Base):
pass
class MyModel2(Base):
field = models.IntegerField()
Step 1 and 2 - Rename field and create in base class
class Base(models.Model):
field = models.IntegerField()
class MyModel1(Base):
pass
class MyModel2(Base):
old_field = models.IntegerField()
Step 3 - moving data
Will work -
for obj in MyModel2.objects.all():
obj.field=obj.old_field # the same as obj.base_ptr = obj.old_field; obj.base_ptr.save()
obj.save()
Won't work -
MyModel2.objects.all().update(field=models.F('old_field'))