Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
queryset update using F() object don't works in datamigrations

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

  1. rename the old fields in child
  2. create the new fields in parent
  3. move data from old fields to new fields
  4. delete the old fields

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'))
about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda