Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set default field value to value of other field in a 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 make the fullname field default to name? As it is right now, the fullname defaults to the string representation of the name CharField.

Example:

new MyModel(name='joel')

would yield 'joel' as both name and fullname, whereas

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

would yield different name and fullname.

like image 289
Joel Avatar asked Aug 13 '10 09:08

Joel


People also ask

What is auto field in Django?

According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

How do you add a new field to a model with new Django migrations?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.


1 Answers

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
like image 53
Dominic Rodger Avatar answered Oct 06 '22 08:10

Dominic Rodger