0

I have a model and one of it's fields is defined as blank=True, null=True. I changed both to False and wrote a callable function that returns random strings. I set that function as the default= of that field, and then I ran makemigrations and migrate, but I keep seeing blank fields in my table.

Is that expected behaviour? And if so, how can I populate all existing fields?

I'm using Django 1.10

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • default value is what the ORM layer returns if no value in the database for that field. Applying makemigrations and migrate should not change the values in the database. You can check this `https://stackoverflow.com/questions/29787853/django-migrations-add-field-with-default-as-function-of-model` in case you want to Alter field values. – Arpit Goyal Oct 20 '17 at 17:02
  • @ArpitGoyal This is not a DateField, (nor Time), so `auto_now` won't work for me. – alexandernst Oct 20 '17 at 17:06
  • Something that you can do is set `null=False` and `blank=False`and run migrations so Django show a message saying that you have to provide a value for those empty fields and you put `str('random_message')` and exit from the shell – Mauricio Cortazar Oct 21 '17 at 00:29

1 Answers1

3

Directly applying makemigrations and migrate does not update the data for the field with the default value returned by your function..

In your Migration class you can write a function that achieves so (updating the values in your database)

# -*- coding: utf-8 -*-
# Generated by Django A.B on YYYY-MM-DD HH:MM
from __future__ import unicode_literals

from django.db import migrations
import uuid

def gen_uuid(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    for row in MyModel.objects.all():
        row.uuid = uuid.uuid4()
        row.save(update_fields=['uuid'])

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0004_add_uuid_field'),
    ]

    operations = [
        # omit reverse_code=... if you don't want the migration to be reversible.
        migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    ]

Source: Django Writing Migrations (populate_uuid_values.py)

Blairg23
  • 11,334
  • 6
  • 72
  • 72
Arpit Goyal
  • 2,212
  • 11
  • 31