Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Django Project Setup with Database Routing and Custom Models

Tech Aug 19 17

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
Tags: Django

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.