Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model: NULLable field

I'm working on a django project where I need a DateField to sometimes be empty. My model looks like this:

#models.py end = models.DateField(default=None, blank=True) 

But when I run python manage.py sql myapp the sql statement always end up being

CREATE TABLE "myapp_date" ( "end" date NOT NULL ); 

Therefore my field isn't nullable and I can't understand what I should do to make it so. Any idea would be appreciated !

like image 665
Robin Avatar asked Apr 16 '13 20:04

Robin


People also ask

How do you make a field nullable in Django?

null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.

How do I allow null values in Django model?

So, if you want to save blank field you need to allow it on Django and Database level. blank=True - will allow empty field in admin panel null=True - will allow saving NULL to the database column.

What is null and blank in Django models?

null is purely database-related, whereas blank is validation-related. If a field has blank=True , form validation will allow entry of an empty value. If a field has blank=False , the field will be required.

How do I check if a field is NULL in Django?

Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None .


1 Answers

You should use

end = models.DateField(default=None, blank=True, null=True) 

Basically blank allows you to pass it a null value, but null tells the database to accept null values.

like image 157
Ngenator Avatar answered Oct 01 '22 21:10

Ngenator