'Update new field for all users upon migration

I learned Django recently. Now on one of the projects I'm working on, I need to add a new field, is_core_administrator to model UserProfile, which will set the oldest user as a core administrator. I need to update this field for all users with migration. Is there a way to do this? I mean, when I make migrations, is it possible to update this field to true for the ​oldest user, and false for rest. Finding the oldest user will not be difficult since we already have another field DateJoined. I just want to update the corresponding field on making the migration.



Solution 1:[1]

Sure, just use migrations.RunSQL or migrations.RunPython depending on your requirements.

The latter could be easier to use in this case, but you should be able to do this with a single UPDATE SQL statement too.

Solution 2:[2]

You could do that using RunPython option in Django migrations.

Create a function at the top of the migration file.

def set_default_values(apps, schema_editor):
    # Set the defualt values

Add the below line before the alter field operation in the migration file.

RunPython(set_default_values)

Solution 3:[3]

Please clarify your use case. I see that you have three options:

  1. You might need migrate command to perform this modification every time you migrated your program. If this is so, you need to add a small loop to the end of the script that would be generated by makemigrations and if you ship your program to the production environment with the modified migration script you will be able to do so.
  2. If you need this as a one time only modification for your development environment, I suggest it is better not to modify migration script but to change is_core_administrator by using Django shell manually.
  3. If you need to program to set its first created UserProfile with is_core_administrator set True where and when ever installed, I suggest the easiest way is to define save(self): and to check within if the object you are going to save is the first instant probably by using UserProfile.objects.count() or UserProfile.objects.exists() and set is_core_administrator accordingly. Maybe something like following:
class UserProfile(models.Model):
    ...
    ...
    is_core_administrator=models.BooleanField(default=False)
    def save(self, force_insert=False, force_update=False, using=None, 
        update_fields=None):
        if not UserProfile.objects.exists():
            self.is_core_administrator=True
        self.etiket=self.woo_name
        return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX
Solution 2 Manu mathew
Solution 3 Can Baysal