Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
For data to be helpful in any application, it must follow certain principles. Django models can use various data types to ensure that model data follows particular rules (e.g., number, text, email).
The database fields defined by a Django model are the most significant and only required aspect. Class attributes define which fields are available. Choose field names that don't conflict with the model API(Application Programming Interface), such as clean, save, or delete.
What are Models in Django?
A model in Django is a class that contains all of the necessary fields and methods. Each model class corresponds to a single database table.
Model in Django is a ‘django.db.models’ subclass.
A Database field(column) is represented by the model and each field of the model class.
Django has a database abstraction API that lets us create, update, get and delete records from a mapped table.
The ‘Models.py’ file defines the model. Multiple models can be stored in this file.
What are fields in Django?
To set the field for any form of data is similar to selecting a data type in C or C++ for storing a specific integer, char, or any other value.
Fields are data types in Django that hold a specific type of data. IntegerField, for example, would be used to store an integer. These fields contain built-in validation for a particular type of data; therefore, you can't put "ABC" in an IntegerField. Likewise, other fields are specific to their purpose. This article focuses on the significant fields used in Django Models.
This blog focuses on Django model data types and field list concepts.
Django model data types and field list
The appropriate Field class should be used for each field in the Django model. Django uses field class types to determine a few things:
The column type specifies the type of data to be stored in the database (e.g., INTEGER, TEXT, VARCHAR).
When rendering a form field (for e.g., input type=<"text">, <select>), we should use the default HTML widget.
Validation requirements that are utilized in Django's admin and automatically generated forms.
Django comes with several built-in field types that may save any type of data from a number to a complete HTML file document.
It's crucial to realize that Django model data types work on the database and Django/Python layers. Django produces and executes a model's DDL (Data definition language) to construct a database table when defining a Django model with its data types and creating its initial migration. This DDL comprises rules that reflect a Django model's fields (e.g., a Django IntegerField model field gets translated into an INTEGER DB column to enforce integer values). This means that if we change this type of Django model field (for example, from an integer to a text field), we'll need to create a new migration for the database table to reflect the new rule.
An example showing Django model data types and field list:
from django.db import models
class Actor(models.Model):
firstName = models.CharField(max_length=150)
lastName = models.CharField(max_length=150)
rating = models.IntegerField()
class Movie(models.Model):
actorName = models.ForeignKey(Actor, on_delete=models.CASCADE)
movieName = models.CharField(max_length=150)
releaseDate = models.DateField()
numStars = models.IntegerField()
You can also try this code with Online Python Compiler
The following is the list of all types of fields in Django.
Django model Field Name
Description
models.BinaryField()
Creates a blob(binary large object) field in which binary data can be stored (e.g., images, audio or other multimedia objects)
models.nullBooleanField()
Creates a boolean field in which True/False (or 0/1) values are stored and allows the NULL values.
models.BooleanField()
Creates a boolean field in which True/False (or 0/1) values are stored.
models.TimeField()
To store the time, this function creates a time field.
models.DateField()
Creates a date field that can be used to store dates.
models.DateTimeField()
Creates a date-time field that is used to store dates and times.
models.AutoField()
Creates an auto-incrementing integer, which is typically used for custom primary keys.
models.DurationField()
Creates a field for storing time periods or intervals.
models.IntegerField()
Creates a column for integer numbers to be stored.
models.BigIntegerField()
To fit the numbers between -9223372036854775808 and 9223372036854775807, make a big integer. Depending on the DB brand, this range may differ.
models.PositiveIntegerField()
Values from 0 to 2147483647 are enforced. Works similarly to IntegerField, but only accepts positive numbers as input.
models.PositiveSmallIntegerField()
Values ranging from 0 to 32767 are enforced. Similar to IntegerField and the specialized PositiveIntegerField, but with a lower positive range.
models.SmallIntegerField()
Ensures that the number is between -32768 and 32767. IntegerField-like functionality, but with a narrower integer range.
models.FloatField()
Creates a column in which floating-point numbers can be stored.
models.DecimalField(decimal_places= Y,
max_digits= X)
Ensures that a number has no more than X digits and Y decimal points. To store decimal numbers, this function creates a decimal field. It's worth noting that both the X and Y parameters are necessary, with the X being the maximum number of digits to store and the Y representing the number of decimal places to store.
models.CharField(max_length= N)
When creating a text column, the max_length argument is necessary to indicate the maximum length in characters.
models.TextField()
Creates a text field in which you can store text.
models.EmailField()
Uses the internal Django EmailValidator to identify what is and isn't a valid email and enforces it. It works similarly to CharField, with a max length of 254 characters and the string’s requirement to be a valid email.
models.FileField()
Enforces and provides numerous file-handling facilities (e.g., file opening/closing, upload the location, and so on). Works similarly to CharField, with a max length of 100 characters and the string’s requirement to be a valid file.
models.FilePathField()
Limits the filename possibilities in the filesystem directories by enforcing and providing various functions. It behaves similarly to CharField, with a max length of 100 characters and requiring the string to be a legitimate file in a filesystem directory.
models.ImageField()
Enforces and provides various image-related functions (e.g., getting the height and width). Works similarly to CharField and the specialized FileField, with a maximum length of 100 characters and the requirement that the string is a valid image. It's worth noting that this field necessitates the presence of the Pillow Python library (e.g., pip install Pillow).
models.SlugField()
Enforces a slug string consisting entirely of letters, digits, underscores, and hyphens. Works in the same way as CharField does, with a max length of 50 characters and a check if the provided string is a slug — a concept commonly used to clean URL(Uniform Resource Locator) strings containing spaces and other possibly incorrect characters like letters with accents.
models.GenericIPAddressField()
Only accepts valid IPv4 or IPv6 addresses (e.g. 198.10.11.28 and FE71::8282:B7FF:FE0E:9769, as well as functions like unpack_ipv4 and protocol). It behaves similarly to CharField, with a max length of 39 characters and requiring the string to be a valid IP address.
models.UUIDField()
A field for storing universally unique IDs. The UUID(Universally Unique Identifiers) class of Python is used. This stores in a UUID datatype in PostgreSQL, otherwise in a char data type (32).
models.URLField()
URLValidator validates a CharField for a URL.
Django Models - Field Relationships
ForeignKey
OneToOneField
ManyToManyField
ForeignKey
In order to limit the amount of data that may be contained in the foreign key table, a foreign key (FK) is a column or combination of columns that is used to create and enforce a link between the data in two databases. Use models to make a recursive relationship: an object having a many-to-one relationship with itself.
When one record from one model A is identically related to one record from another model B, this is the method employed. In this case, each table can only have one record. This is similar to the Foreign Key with unique = True in terms of concept, but the ‘reverse’ side of the relation will yield a single object.
ManyToManyField
When a model has to refer to several instances of another model, a ManyToMany field is utilised. Use the ManyToManyField to specify a many-to-many relationship.
Frequently Asked Questions
What are Field options in Django model data types and field lists?
Each field has a set of arguments for setting column properties. For example, to define the varchar database, CharField requires max_length. These are called Field options in Django model data types and field lists. Some field options are Null, Blank, Choices, Default, help_text, primary_key and Unique.
What is the purpose of Django Field types?
The Django Field type determines the type of database column and the field type also specifies the minimal validation requirements used in the Django Model.
How to add fields in Django models?
A new field can be easily added to a model, migrations can then be initialised with./manage.py makemigrations, and the new field will be added to your database when you run./manage.py migrate. With the new migration feature added in Django 1.7, all of this is achievable.
How to create custom model fields in Django?
Some steps need to be followed for creating custom model fields. Custom model fields can be created using individual database types, and Python objects are transformed into query values, transforming query results into database values. A model field's form field must be specified. field data transformation for serialization.
Conclusion
We have learned the concepts of Django model data types and field lists. Fields are data types in Django that hold a specific type of data. Django models use various data types to ensure that model data follows particular rules. We learned different field lists and data types in the Django model.
Go through The Basics of Django Framework to deeply understand the concept of Django, which will be helpful in Django model data types and field lists.