Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How change all values of a colum to null?

I have a problem, I make some changes in my models, because I had an Integer field that had to be changed to a ForeignKey

Well for error I assign to all the objects in the field derived_to the value 1.

I would now like to mark all the rows in this column as null. How can I make this? these are my last two migrations

class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0026_auto_20170603_1517'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='workorder',
            options={'verbose_name': 'work order', 'verbose_name_plural': 'work orders'},
        ),
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
           field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        preserve_default=False,
    ),
]

And the last one

class Migration(migrations.Migration):

    dependencies = [
        ('work_order', '0027_auto_20170605_0836'),
    ]

    operations = [
        migrations.AlterField(
            model_name='workorder',
            name='derived_to',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
        ),
    ]

Well thats all i need to make a new migration to assign null to all the objects in work_order in the column derived_to, because now all the objects have derived_to pointing to the first register on OutsourceOptions and that is not correct.

Thanks and sorry for my bad English.

like image 884
marcosgue Avatar asked Oct 22 '25 14:10

marcosgue


1 Answers

If I have understood you correctly, you want to set all existing derived_to values to null? You can do that with RunPython

Runs custom Python code in a historical context. code (and reverse_code if supplied) should be callable objects that accept two arguments;

def forwards_func(apps, schema_editor):

    Workorder = apps.get_model('appname','Workorder')
    Workorder.objects.update(derived_to=None)

Add this into the migration like this:

operations = [
    migrations.AlterField(
        model_name='workorder',
        name='derived_to',
        field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'),
    ),
    migrations.RunPython(forwards_func),
]
like image 67
e4c5 Avatar answered Oct 24 '25 20:10

e4c5