Django Models Outside Apps

In this blog, we will discuss an approach to use the same database table for CRUD operations from different Django applications.

Illustrating the basic structure of Django app below:

Generally, In Django each model maps to a single database table. Each Model is a class and its subclass of  django.db.models.Model.
If we want to create multiple apps in a single Django project for web, mobile version 1 and mobile version 2 etc. Implementing  model class in models.py file of Django application is not efficient. We can create models folder at project level.

Step 1: Create a folder  named models at your project directory. We will make a sample migration file vehicle.py in the models folder.

vehicle.py
from django.db import models
# Creating a vehicle table in Postgres
class Vehicles(models.Model):
    id = models.BigAutoField(primary_key=True)
    vehicle_no = models.BigIntegerField(unique=True)
    name = models.CharField(max_length=30)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    type = models.SmallIntegerField()
    color = models.CharField(max_length=30, blank=True, null=True)

    class Meta:
        db_table = 'vehicles'
        unique_together = (('vehicle_no', 'type'),)

Here we are creating  vehicles table in Postgresql database. id, vehicle_no, name, price, type  and color are fields of the model. Each field is  a class attribute and each attribute maps to a database column.

Model Meta is the inner class of your model class, it has a lot of options. Options are used to change the behavior of model fields.

db_table  parameter is used to override the table name. Otherwise, table name by default derives from a combination of your app_lable and Model’s class name like app_label- Model’s class .

Step 2:   In your settings.py file, you will find INSTALLED_APPS. It is a list of all of the places to look for models, default apps, our custom apps and other utilities. Mention your ‘models’ folder in  INSTALLED_APPS.

Step 3: Run command  Python manage.py migrate. It will create a table for  a vehicles model in your database.

Your Django project structure will look like this:

Now you can use the vehicles model in all Django applications.




Shraddha Falane

Shraddha Falane