Defaults and Empty Fields
Part of the Models and the Admin section of Coddy's Django journey. Lesson 3 of 23.
Save a book without saying whether you read it, and the database refuses: NOT NULL constraint failed. Every field is required until you say otherwise, with one of three options:
has_subtitles = models.BooleanField(default=True)
rating = models.DecimalField(max_digits=3, decimal_places=1, null=True, blank=True)
tagline = models.CharField(max_length=200, blank=True)default is the value a new row gets when you give none. null=True lets the column store NULL, which Python reads as None. blank=True lets forms and the admin accept the field empty.
A number or a date you may not know needs both null=True and blank=True. Text needs only blank=True: empty text is stored as "", and null would give it two kinds of empty. TextField is text with no length limit, for something long like a review.
Challenge
EasyMake the optional parts of Book optional:
is_readstarts asFalse.finishedmay be empty: an unfinished book has no date.- A new field
summary: long text, no length limit, may be empty, the Django way for text.
Press Run, then in the Shell tab type Book.objects.create(title="Emma", author="Jane Austen", year=1815, price="7.50") and open the Data tab.
Try it yourself
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2)
is_read = models.BooleanField()
finished = models.DateField()
All lessons in Models and the Admin
1Your First Model
Your First ModelField Types2Querying with the ORM
Creating RowsAll and GetFilter and LookupsCounting RowsSorting RowsUpdate and DeletePractice on your own: Django playground