Django Models
Models are the data access layer of your application. Every Django application gets a models.py file by default to create database tables. The default database engine in Django framework is sqlite3. It can be changed by visiting settings.py under the project directory. Django uses ORM (Object Relational Mapping) that allows us to perform database operations without writing SQL queries but with simple python objects.
from django.db import models
models is a module that packs the definitions for Model classes, different models fields, and field relationships.
To create a table in simply make a class subclassing the Model class.
class MyClassname(models.Model):
...
Django Model Fields
Django version 2.2 offers 26 different field types to capture different data formats. For simplicity, we have grouped them according to functionality rather than alphabetical sorting.
Django Models - Field Types
- AutoField
- BigAutoField
- UUIDField
- IntegerField
- PositiveIntegerField
- SmallIntegerField
- PositiveSmallIntegerField
- BigIntegerField
- DecimalField
- FloatField
- BinaryField
- BooleanField
- NullBooleanField
- CharField
- TextField
- EmailField
- SlugField
- URLField
- GenericIPAddressField
- DateField
- TimeField
- DateTimeField
- DurationField
- FileField
- FilePathField
- ImageField
Django Models - Field Options
The following arguments are available in Django field types:
- null
- blank
- choices
- db_column
- db_index
- db_tablespace
- default
- editable
- error_messages
- help_text
- primary_key
- unique
- unique_for_date
- unique_for_month
- unique_for_year
- verbose_name
- validators
Django Models - Field Relationships
Sometimes business logic requires relationships among attributes of different model classes. There are three field relationships in Django models:
ForeignKey(),
OneToOneField() and
ManyToManyField().
Django ForeignKey
ForeignKey is like a many-to-one relationship. It requires two positional arguments namely Classname and on_delete.
Classname is the class to which the model is related.
on_delete=models.CASCADE means when the Superclass object is deleted all its reflections as ForeignKey also gets deleted. For example, when the Customer object in the below model is deleted its related Order objects are also deleted.
class Customer(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
order_details = models.TextField()
Django OneToOneField
OneToOneField is very similar to ForeignKey except the relationship is like unique=True.
For example, if one person can have only one nationality it can describe as below:
class Person(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Citizenship(models.Model):
person = models.OneToOneKey(Person, on_delete=models.CASCADE)
country = models.CharField(max_length=30)
Django ManyToManyField
A many-to-many relationship requires only one argument i.e, the class to which the model is related. It can be understood with the example below:
class Person(models.Model):
name = models.CharField(max_length=30)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(
Person,
through='Membership',
through_fields=('group', 'person'),
)
class Membership(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
inviter = models.ForeignKey(
Person,
on_delete=models.CASCADE,
related_name="membership_invites",
)
invite_reason = models.CharField(max_length=64)
Use MySQL as Database Engine
Step 1: Download MySQL from usi .msi file. Select 'Server only' when prompted
https://dev.mysql.com/downloads/installer/
Step 2: Install python mysql client
pip install pymysql
Step 3: Under __init__.py mention
import pymysql
pymysql.install_as_MySQLdb()
Step 3: Select database engine under settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 3306,
}
}
Note: Replace query = query.decode(errors='replace') with query = errors='replace' in operations.py if required.
Use PostgreSQL as Database Engine
Step 1: Download postgresql from
https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
Step 2: Install python postgresql client
pip install psycopg2
Step 3: Select database engine under settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER': 'postgres',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': 5432,
}
}