Django Project Setup with Database Routing and Custom Models
Initialize Project Structure
Begin by scaffolding a new Django project. Navigate to your desired workspace and run the following command:
django-admin startproject marketplace
To integrate MySQL as the database backend, ensure pymysql is configured in your project's __init__.py file:
import pymysql
pymysql.install_as_MySQLdb()
Database Configuration and Routing
In your settings.py, configure the primary and replica databases. This setup supports read/write splitting, where writes are directed to the primary instance and reads are offloaded to a replica.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'marketplace_db',
'USER': 'db_user',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306',
},
'replica': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'marketplace_db',
'USER': 'db_user',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
Create a router in utils/router.py to enforce these constraints:
class DataAccessRouter:
def db_for_read(self, model, **hints):
return 'replica'
def db_for_write(self, model, **hints):
return 'default'
def allow_relation(self, obj1, obj2, **hints):
return True
Register the router in settings.py:
DATABASE_ROUTERS = ['utils.router.DataAccessRouter']
Abstract Base Models
To standardize audit fields across the application, define an abstract base class. This avoids redundant code in your model definitions.
from django.db import models
class TimestampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created Date')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Updated Date')
class Meta:
abstract = True
Modell Implementation
Organize your logic by creating dedicated apps: catalog, accounts, and orders. Configure a custom user model in settings.py by referencing the model class:
AUTH_USER_MODEL = 'accounts.User'
In accounts/models.py, extend the default user management:
from django.contrib.auth.models import AbstractUser
from utils.models import TimestampedModel
class User(AbstractUser, TimestampedModel):
class Meta:
db_table = 'app_users'
Schema Migration
Create the required database in MySQL, then synchronize your models with the data base schema using Django migration tools:
# In MySQL shell
CREATE DATABASE marketplace_db CHARACTER SET utf8mb4;
# In terminal
python manage.py makemigrations
python manage.py migrate