As you already know, Django web applications can access and manage data with Python objects — models. Models specify the structure of the stored data. The model definition must not depend on the selected database because once you choose the database you want to use in your project, you don't have to work with it directly. You write your model structure, and Django does all the work related to the database. There are many different types of models. In this topic, we will take a closer look at the most common ones: DecimalField, FloatField, IntegerField, BooleanField, CharField, TextField, DateField and FileField.
Model example
Let's imagine that we want to create a bookstore application. We'll start with creating two models in the models.py file: one for storing information about books and another for authors.
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=64)
abstract = models.TextField(max_length=1000)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
pages = models.IntegerField()
price = models.DecimalField(max_digits=8, decimal_places=2)
publication_date = models.DateField(null=True, blank=True)
is_in_stock = models.BooleanField()
file = models.FileField(upload_to='books/')
class Author(models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
country = models.CharField(max_length=64)
Each created model must be inherited from models.Model so that Django realizes that this class serves as a description of the model. A model can have any number of fields of any type, and each field is a column of data that we want to store in one of our database tables. In the following paragraphs, we'll consider each field type in detail.
Numeric fields
Let's explore the numeric fields, such as IntegerField, FloatField and DecimalField.
Let's start with the IntegerField. It stores whole numbers without any fractional components. It represents a signed 32-bit integer value in the database. This field commonly stores numerical data that should be treated as integers, such as counts, IDs, or any other whole-number value. In our example, we use it to store the number of pages in a book:
pages = models.IntegerField()The FloatField is designed to store floating-point numbers with a decimal component. It represents a double-precision floating-point number in the database. This field is suitable for storing numerical data requiring precision and can have fractional values, such as measurements, percentages, or other real numbers.
The DecimalField is specifically designed for storing fixed-point decimal numbers. It allows you to specify the total number of digits and the number of decimal places for precise decimal representation. This field is commonly used when dealing with financial or monetary values that require exact decimal calculations, such as prices, currency amounts, or tax rates.
price = models.DecimalField(max_digits=8, decimal_places=2)The max_digits parameter specifies the maximum number of digits that can be stored in a DecimalField. This number includes both the digits before and after the decimal point. max_digits value must be a positive integer.
As to decimal_places, this parameter allows you to specify the number of decimal places stored in a fixed point number. This argument determines the precision of the number when it comes to decimal places after the dot. The decimal_places value can be any non-negative integer. If you do not specify this argument when defining DecimalField, then the default value is decimal_places=0, which means that the field will only store integer values.
BooleanField
The BooleanField in Django is a field used to store boolean values in the database. It represents a simple on/off or true/false state. In our application, we'll use it to store information on whether a book is in stock or not:
is_in_stock = models.BooleanField()BooleanField accepts and stores the following values:
True, which represents a positive or a true state;False, which means a negative or a false state.
BooleanField can be used in various scenarios, such as representing flags, checkboxes, or binary choices in your models.
CharField
Consider the following line from the snippet above:
title = models.CharField(max_length=64)This means that the model will have a field named title, and the type of this field will be models.CharField. This type describes string fields with the maximum number of characters specified in the max_length parameter. This is how you can store data such as names, last names, and addresses, as they do not require many characters.
The important thing is that the field name is used to reference and manipulate the data in queries and templates. Moreover, the order in which the fields are declared will affect their default order if, for instance, the model is displayed in the form (Django can automatically create a web form to fill in all the data required to make a record of a particular model, but we'll get to this later).
models.CharField has only one required parameter: max_length.
TextField
Let's consider the abstract field in the Book model:
abstract = models.TextField(max_length=1000)As you can see here, the type used to describe the abstract field is models.TextField. However, unlike CharField, the max_length parameter has a value of 1000. This type stores big-string data, for example, large texts or paragraphs.
The main differences between CharField and TextField are:
max_lengthenforcement.CharFielddoes it on the database level, whileTextFieldwill only do that in the auto-generated form widget;maximum
max_length. The maximum length of theVarcharfield, whereCharFielddoes the mapping, may be restricted to 255 by some database engines; useTextFieldif you want to store more characters.
For models.TextField, it is not necessary to specify the maximum possible number of characters (max_length). So you can quickly write it without any parameters.
DateField
In our models, we used DateField to store a book's publication date. In Python, this type is represented by an instance of datetime.date. There are no required parameters for this type, but as you can see, we specified two: null=True and blank=True. Here is what they mean:
if
null=True, Django will store empty field values asNULLin the database. If no value is specified, it will default toFalse.if
blank=True, the field can be blank when filling out the forms. The default value isFalse.
These parameters are general for any field type so that you can specify them for any field.
FileField
The FileField is a field used to handle file uploads. It allows users to upload files from their local system to your Django application. The FileField stores the uploaded file's reference and automatically handles the file storage and retrieval.
file = models.FileField(upload_to='books/')The upload_to parameter specifies the directory path where the uploaded file will be stored. It can be either a string representing a path or a callable function that dynamically determines the upload path based on the instance and filename. When a file is uploaded using a FileField, Django automatically stores the file in the specified location and generates a unique filename. It also provides methods to access and interact with the stored file.
ForeignKey
Take a look at this line in the Book model:
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)This means that this model will store a reference to some record from another model. In this case, the Author model. This relationship makes sense because we want to know who wrote a certain book. The models.ForeignKey field type defines this relationship between the two models. In this example, on_delete and null are the field parameters.
Conclusion
In this topic, you have learned several field types that can be used in Django models. There are many other fields, but now you know how to work with the most commonly used ones. Refer to the documentation for more information about all the fields and their parameters. Now let's practice what you've learned!