[Solved]-How do I set default field value to value of other field in a Django model?

8👍

I wonder if you’re better off doing this via a method on your model:

class MyModel(models.Model):  
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100)

    def display_name(self):
        if self.fullname:
            return self.fullname
        return self.name

Perhaps, instead of display_name this should be your __unicode__ method.

If you really want to do what you’ve asked though, then you can’t do this using the default – use the clean method on your form instead (or your model, if you’re using new-fangled model validation (available since Django 1.2).

Something like this (for model validation):

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100,default=name)

    def clean(self):
      self.fullname=name

Or like this (for form validation):

class MyModelForm(ModelForm):
    class Meta:
       model = MyModel

    def clean(self):
        cleaned_data = self.cleaned_data
        cleaned_data['fullname'] = cleaned_data['name']
        return cleaned_data

4👍

How about making a migration with a default value, and then adding custom data migration to your migration file? Here’s a complete migration file example:

from datetime import timedelta

from django.db import migrations, models
import django.utils.timezone


# noinspection PyUnusedLocal
def set_free_credits_added_on(apps, schema_editor):
    # noinspection PyPep8Naming
    UserProfile = apps.get_model('core', 'UserProfile')
    for user_profile in UserProfile.objects.all():
        user_profile.free_credits_added_on = user_profile.next_billing - timedelta(days=30)
        user_profile.save()


# noinspection PyUnusedLocal
def do_nothing(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('core', '0078_auto_20171104_0659'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='free_credits_added_on',
            # This default value is overridden in the following data migration code
            field=models.DateTimeField(
                auto_now_add=True,
                default=django.utils.timezone.now,
                verbose_name='Free Credits Added On'
            ),
            preserve_default=False,
        ),
        migrations.RunPython(code=set_free_credits_added_on, reverse_code=do_nothing),
    ]

Here the free_credits_added_on field is set to 30 days before the existing next_billing field.

Leave a comment