[Answered ]-When should I be using null=False on django model fields

1👍

NOT NULL is a tool to enforce data integrity if that column must never be empty, which is always a good thing. It’s better to error out hard and early, than to discover later on that something went wrong and you’re left with inconsistent or missing data. Data integrity is a big part of database design, so you should use all the tools at your disposal.

Do you need it? No. Should you use it when appropriate? Definitely. Have I used null=True when I should have been using null=False? Yes I have. If your code works as it should, there’s no reason to use null=False. But bugs happen, and when they happen, you don’t want to discover that half your data is wrong.

👤knbk

1👍

The general rule I have heard/used is that your database should be as strict as possible in what it accepts; your DB is your understanding of the world, and precluding bad data (or at least calling your attention to it) is a good trait.

(The field parameters are also useful when you want to generate right data with model_mommy; it will only generate data that fits your fields, so making them narrowly tailored helps CYA and write good tests.)

The default is False, so the easy road is the right one. Just mark what you need nullable 🙂 .

EDIT: One place where you may need nullability is in polling foreign data. If you are mirroring an API that will use new objects in data before it tells you that there are new objects, then you will want data about that object to be nullable to avoid failing to save new data.

For example:

class Person(models.Model):
    """ A person that might tweet """
    name = models.CharField(max_length=200)

class Tweet(models.Model):
    """ A message broadcast by a person. """
    msg = models.TextField()
    person = models.ForeignKey('Person')

if you are scraping tweets and hit a new Person’s tweet before you save that Person, you might get_or_create an object to fill Tweet.person. However, you don’t know that Person’s name; you would want name to be nullable (and probably to run an integrity task on your DB regularly to find and fix these issues.)

0👍

Its part of your duty as backend developer to set the mimimum data is required to have the model defined, if some field isnt null=True or blank=True the database wont allow you to save the model since they required that data to write the row. (inner coherence is a basic behaviour in SQL databases)

So when a field is not required you should mark it as blank=True or Null=True, and its your duty to mark them properlly.

As a plus django uses that data for the forms validation so doing that correctly will help you later on.

Leave a comment