DEV Community

Cover image for SQL Schema in Django Models
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Edited on • Originally published at Medium

10 3

SQL Schema in Django Models

A schema in a SQL database is a list of logical data structures. It's commonly used for security-related management and permissions.

The feature is supported by PostgreSQL and very well by Django.
Let's see how to configure schema in Django for a PostgreSQL database.

Creating the database

First, ensure that the database is created.

CREATE DATABASE coredb;

CREATE USER core WITH PASSWORD '12345678';

GRANT ALL PRIVILEGES ON DATABASE coredb TO core;
Enter fullscreen mode Exit fullscreen mode

And let's create a schema.

CREATE SCHEMA AUTHORIZATION core;

CREATE SCHEMA IF NOT EXISTS coreschema AUTHORIZATION core;
Enter fullscreen mode Exit fullscreen mode

We've created coreschema in the coredb database. And only the core user can access the schema for the moment.

Let's see how to use it with Django.

Django models configuration

Naturally, make sure that the Django project is configured with Django. It'll look like this.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'coredb',
        'USER': 'core',
        'PASSWORD': '12345678',
        'HOST': 'localhost',
        'PORT': 5432
    }
}
Enter fullscreen mode Exit fullscreen mode

And when working with a model, use the Meta class to tell Django the name of the database table to use for the model.

class Fruit(AbstractModel):

    name = models.CharField(max_length=100)

    class Meta:
        db_table = '"coreschema""fruit"'
Enter fullscreen mode Exit fullscreen mode

And run the migrations commands. And the table will be created under coreschema.

Want to add something or have some comments? Let's discuss this in the comments section.

Article posted using bloggu.io. Try it for free.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more