How to set default field value for another field value in Django model?

If I have the following model in django;

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

How do I change the default full name name? As of now, fullname by default has a string representation of the CharField name.

Example:

 new MyModel(name='joel') 

will give "joel" as the name and full name, whereas

 new MyModel(name='joel',fullname='joel karlsson') 

will give a different name and full name.

+6
django django-models
source share
2 answers

I wonder if you'd better do this using 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 requested, then you cannot do it with default - use the clean method in your form (or your model, if you use the new -fangled model check (available with 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 
+7
source share

How to make a migration with a default value and then add a custom data migration to the migration file? Here is an example migration file:

 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 free_credits_added_on set 30 days before the existing next_billing field.

+1
source share

All Articles