Tutorial #6 — Introduction to Django Model Design and it’s optional keyword arguments.
In the previous tutorial we have discussed about the directory structure and basic django setup. Now we will discuss most important and crucial part of back-end engineering that is the database design. What should be the relationships and what are the attributes that are needed to define the relationships. Django Framework has Object Relational Mapping, in which you can design your database relations by writing simple classes.We will discuss, frequently used django fields (data types) and their optional keyword arguments. Then we will discuss the differences among unique, null, blank and other constraints.
Frequently Used Django Fields Options
(1) null — If True
, Django will store empty values as NULL
in the database. Default is False
.
(2) blank — If True
, the field is allowed to be blank. Default is False
.If a field has blank=False
, the field will be required.
(3) default — The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
(4) primary_key — If True
, this field is the primary key for the model.If you don’t specify primary_key=True
for any field in your model, Django will automatically add an AutoField
to hold the primary key, so you don’t need to set primary_key=True
on any of your fields unless you want to override the default primary-key behavior.
(5) unique — If True
, this field must be unique throughout the table.This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique
field, a django.db.IntegrityError
will be raised by the model’s save()
method.
(6) verbose_name — A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
Frequently Used Django Model Fields
(1) CharField ()— This is used, when we need to declare particular attribute in database relation as string with limited number of characters.
max_length is required argument for CharField . It is validated at DB Level.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
This will create unique blog_id field with constraint of maximum length 25.
(2) TextField() — This is used, when the maximum length of attributes is not known before hand.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField()
(3) IntegerField() — The numeric attributes of database relations are defined as the IntegerField. It takes both positive and negative integers.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
(4) BooleanField() — This Field is used for attributes with boolean values i.e. true/false. Default is None Type, it is neither True nor False. We have to explicitly define the default argument.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
(5) DecimalField() — This is used, when we need to store numeric data with the some precision.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
avg_rating = models.DecimalField(max_digits=3,decimal_places=2)
Here avg_rating will be floating point values with 3 maximum allowed digits and 2 digits precision. For example — 4.75, 3.72, 4.56
(6) EmailField() — A CharField
that checks that the value is a valid email address using EmailValidator
.
(7) ImageField() — Inherits all attributes and methods from FileField
, but also validates that the uploaded object is a valid image.In addition to the special attributes that are available for FileField
, an ImageField
also has height
and width
attributes.
Requires the Pillow library.ImageField
instances are created in your database as varchar
columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length
argument.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
avg_rating = models.DecimalField(max_digits=3,decimal_places=2)
thumbnail = models.ImageField(upload_to='images/thumbnails')
(8) URLField() — A CharField
for a URL, validated by URLValidator
.Like all CharField
subclasses, URLField
takes the optional max_length
argument. If you don’t specify max_length
, a default of 200 is used.
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
avg_rating = models.DecimalField(max_digits=3,decimal_places=2)
thumbnail = models.ImageField(upload_to='images/thumbnails')
medium_url = models.URLField()
(9) DateTimeField() — This Field is used when we need to store timestamp of the object creation or updation. It is date and time, represented in Python by a datetime.datetime
instance.
DateTimeField.auto_now -:
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps.
DateTimeField.auto_now_add -:
Automatically set the field to now when the object is first created. Useful for creation of timestamps.
DateTimeField -
: default=timezone.now
- from django.utils.timezone.now()
from django.db import modelsClass Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
avg_rating = models.DecimalField(max_digits=3,decimal_places=2)
thumbnail = models.ImageField(upload_to='images/thumbnails')
medium_url = models.URLField()
published_on = models.DateTimeField(auto_now=True)
(10) ForeignKey() — Used to establish a many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete
option.
from django.db import modelsclass Difficulty(models.Model):
difficulty_id = models.CharField(max_length=10,primary_key=True)
name = models.CharField(max_length=200)
Class Blog(models.Model): blog_id = models.CharField(max_length=25,unique=True)
title = models.TextField(verbose_name = 'Blog Title')
reactdj_score = models.IntegerField(default=10)
published = models.BooleanField(default=False)
avg_rating = models.DecimalField(max_digits=3,decimal_places=2)
thumbnail = models.ImageField(upload_to='images/thumbnails')
medium_url = models.URLField()
published_on = models.DateTimeField(auto_now=True)
difficulty = models.ForeignKey(Difficulty, on_delete=models.CASCADE)
We are concluding the tutorial here with frequently used Django Model Fields and their optional keywords arguments. We will be discussing the Demo Model Design for Blog Management System and Django Migrations basics.
Reference — Django Official Documentation
For Regular Updates and other blogs of the this tutorial series. You may Follow — React DJ Facebook Page
Our series of tutorials are currently organized at — srplabs.in
For Introduction of the Tutorial Series You may read — Building Practical Web Applications with React & Django
📝 Read this story later in Journal.
🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: Get the noteworthy newsletter >