Menu
CoddyTech

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 icon

Challenge

Easy

Add four fields to Book, each with the class that fits what it holds:

  • year: a whole number like 1965
  • price: money up to 9999.99, exact to the cent
  • is_read: yes or no
  • finished: 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Models and the Admin

Practice on your own: Django playground