Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the data is stored.

Each model is a subclass of the class Django.db.models.model. Django has its database access API by which we can make the queries.

The field is the most important part of the model. They are specified by class attributes. To store any data, it is essential to have some rules in it; otherwise, we can easily put some wrong information in any category. To ensure the data fit certain rules, Django models use datatypes. They have an in-built authentication system that checks if the data entered is of the correct data type or not.

Here is an example of the Django model:

from django.db import models
class Actor(models.model):
	first_name = models.CharField(max_length = 50)
	last_name = models.CharField(max_length = 50)
	Age= models.IntegerField()
class Film(models.model):
	lead_actor = models.ForeignKey(Actor, on_delete = models.CASCADE)
	name = models.CharField(max_length = 1000)
	released_date = models.DateField()

Here, in the Actor class, first_name and the last_name are the fields of the model. The fields here are the column name of the mapped table. Remember not to choose field names that resemble the reserve keywords like clean, save or delete. Each field has a class attribute, and each attribute is mapped to a database column of the mapped table. Each field should be a type of the appropriate Field class. Each field is used to determine certain things. These are:

  • The column's data type decides the data to store in the table, e.g., INTEGER, VARCHAR, etc.
  • The HTML widget to render a field
  • The validation which should be used

There are a lot of Field types in Django, and if we want, we can even create new Field types.

Field Types

The major fields types of Django models are as follows:

AutoField

class AutoField(**options)

It creates an integer field that automatically increases.

BigAutoField

class BigAutoField(**options)

Similar to AutoField, just that it is a 64-bit integer and can store numbers up to 9223372036854775807.

BigIntegerField

class BigIntegerField(**options)

It can store 64-bit integers that range from -9223372036854775807 to 9223372036854775807.

BinaryField

class BinaryField(**options)

This can store raw binary data, including Bytes.

BooleanField

class BooleanField(**options)

It is used to store Boolean values such as True and False. The default value of the Boolean field is False unless defined.

CharField

class CharField(max_length = None, **options)

CharField stores is a string field that can store small to large-sized strings. For very large sizes TextField should be used.

DateField

class DateField(auto_now=False, auto_now_add=False, **options)

It stores Date, represented in Python by datetime.date instance.

DateTimeField

class DateTimeField(auto_now=False, auto_now_add=False, **options)

Stores Date and Time, represented in Python by datetime.datetime.

DecimalField

class DecimalField(max_digits=None, decimal_places=None, **options)

It can store decimal numbers up to a fixed precision. The number of decimal places can be defined by the argument decimal_places.

EmailField

classEmailField(max_length=254,**options)

It is also similar to CharField, but it has an additional property to validate if the input text is an email address or not.

FileField

classFileField(upload_to=None, max_length=100, **options)

In this field an user can upload files.

FloatField

class FloatField(**options)

FloatField can store floating point numbers.

ImageField

classImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)

It is also a type of FileField but in addition to that ImageField also validates if the input file is an Image or not.

IntegerField

class IntegerField(**options)

IntegerField can store integers. Integers ranging from -2147483648 to 2147483648 can be stores without any issue. Integers larger than these may result in an overflow.

JSONField

classJSONField(encoder=None, decoder=None, **options)

It is a field for JSON encoded data. This data is represented in the form of a dictionary or list in Python.

NullBooleanField

classNullBooleanField(**options)

This field is similar to Boolean Field with null = True.

PositiveIntegerField

class PositiveIntegerField(**options)

PositiveIntegerField stores integers like IntegerField but validates if the input value is positive. Integers from 0 to 2147483648 can be easily stored.

PositiveSmallIntegerField

classPositiveSmallIntegerField(**options)

It is similar to PositiveIntegerField but only allows integers ranging from 0 to 32767.

TextField

classTextField(**options)

It stores large text. The default widget for TextField is Text Box.

TimeField

classTimeField(auto_now=False, auto_now_add=False, **options)

It is the Time field. In Python, it is represented as datetime. Time.

Apart from these fields, there are many other fields also which can be used in specific cases.

Example to use Model Fields

  • first_name = models.CharField(max_length = 50)

This will create a column of first_name with the datatype of VARCHAR of maximum length 50 in the mapped table.

  • Age = IntegerField()

This will create a column Age with integer as a datatype.

Relational Fields

In addition to the above-specified fields, Django also has a set of fields that represents relations.

Foreign Key

classForeignKey(to, on_delete, **options)

It will create a field with a Many-to-one relationship. It requires two arguments, i.e., the class with which model is related and the on_delete parameter.

ManytoManyField

classManyToManyField(to, **options)

It is a many-to-many relationship. It also requires a single argument, i.e., the class to which the model is related.

OnetoOneField

classOneToOneField(to, on_delete, parent_link=False, **options) A one-to-one relationship, which requires one positional argument, which is the class the model is related to.


Related Topics

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It...

3 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.