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 ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 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 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.

How to Implement Multiple User Types with Django

Django Framework: 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...

3 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

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 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.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 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 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.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.

Django Authentication

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.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 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.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 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.