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 Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

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.

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 – Sending E-mails

Django – Sending E-mails Django comes with a light engine that is ready and simple to use to send emails. Similar to Python, you just need to import a smtplib. You just need to import django.core.mail in Django. Edit the project settings.py file to start sending emails and set  all the following options: EMAIL_HOST – server with smtp.EMAIL_HOST_USER – smtp server login key.EMAIL_HOST_PASSWORD ? Password credential for the smtp server.EMAIL_PORT – server port smtp.EMAIL_USE_TLS or _SSL – if it is secure connection then set True. Simple E-mail Sending To submit a simple e-mail, let's create it a "simpleEmail" view. from django.core.mail import...

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

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

Django Messages

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

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

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

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.

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.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

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.

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 Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

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