Home > Net >  Django - Default value based on another model field
Django - Default value based on another model field

Time:10-22

This is my existing django model

class Account(models.Model):
    env = CharField(max_length=10)

now I need to add period field to my model based on the value of the env field in model. I can get the period value based on the env from following dict in my settings file

mydict = {
    'dev':1,
    'prd':2
}

How do I add my period field to model?

period = Integerfield(default=setvalue from dict)

CodePudding user response:

You can make a custom migration after running makemigrations, you open the migration file created and add a function like this

from django.db import migrations

def set_default_value(apps, schema_editor):
    Account = apps.get_model("YOURAPPNAME", "Account")
    for account in Account.objects.all():
        if account.end == "dev":
            account.period = 1
        elif ...
            ...
        account.save()


class Migration(migrations.Migration):

    dependencies = [
        (...),
    ]

    operations = [
        migrations.AddField(...),
        migrations.RunPython(
            set_default_value,
        ),
    ]

More information about migrations data: https://docs.djangoproject.com/fr/4.1/topics/migrations/#data-migrations

CodePudding user response:

Here is a solution using signals


from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings

class Account(models.Model):
    env = CharField(max_length=10)
    period = Integerfield(blank=True)

@receiver(pre_save, sender=Account)
def account_pre_save(sender, instance, **kwargs):
    if instance.period is None:
        env = instance.env.lower()
        instance.period = settings.mydict.get(env)

I hope that works out for your problem.

  • Related