Field Types
Part of the Models and the Admin section of Coddy's Django journey. Lesson 2 of 23.
A book has more than a title: a year, a price, whether you read it. Each kind of data has its own field class, which sets the column type and the Python value you get back. A film site's Movie could hold:
class Movie(models.Model):
title = models.CharField(max_length=150)
minutes = models.IntegerField()
rating = models.DecimalField(max_digits=3, decimal_places=1)
has_subtitles = models.BooleanField()
released = models.DateField()IntegerField holds whole numbers. DecimalField holds exact decimals and gives back a Decimal: max_digits counts every digit and decimal_places the ones after the point, so 3 and 1 reach 99.9. Money is never a float, because floats are not exact: 0.1 + 0.2 is 0.30000000000000004.
BooleanField holds True or False. DateField holds a datetime.date, a day with no time.
Challenge
EasyAdd four fields to Book, each with the class that fits what it holds:
year: a whole number like1965price: money up to9999.99, exact to the centis_read: yes or nofinished: the day you finished it
Press Run, then type Book._meta.get_field("price") in the Shell tab to see the class you picked.
Try it yourself
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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