Home > OS >  Is it necessary to assign a default value in model field?
Is it necessary to assign a default value in model field?

Time:10-12

As I know in Django, it requires the user to determine the default value for models fields. Like:

class Student(models.Model):
    """Student info"""
    id = models.CharField( max_length=7,primary_key=True,default =-1)
    name = models.CharField(_('name'),max_length=8, default="x"); 

But I'm really annoyed at this. I just don't know what values have to be assgind in the first place. User should make the decision.

Can I just

  1. Give None as the default value? What might be consequences? NPE?
  2. Give a random value.

Is it specific to give a default value to the model field in Django? Or it's general to most MVC web frameworks. Or it's because of the database consideration? Thanks

CodePudding user response:

you can set null=True, blank=True if you dont want that field to be mandatory.

CodePudding user response:

null=True and blank=True are two different things and shouldn't be mixed up.

In order not to have a default field in your model attribute you just need null=True, which basically means "I'm ok with this column storing null values'.

blank=True means that when that attribute appears in a ModelForm it will render the corresponding field as required. Basically it's about form validation.

This might seem like an edge case, especially since a lot of people prefer to write their own forms rather than using Django ModelForm but you know what else uses the ModelForm? The django admin.

Yeah, so unless you want to have that field required also in the django admin then you should add blank=True to your model attribute.

But having blank=True is not going to affect whether you need or not a default value.

CodePudding user response:

If the fields are not mandatory (can be left empty) then you can make them nullable by using null=True. Note that for char fields it is the better practice to use blank=True instead.

For the second thing you mentioned, it is possible to pass a callable to the model field as the default value. So, you can write a function which generates random values and pass that as the field's default value.

  • Related