Django Create Models

If you’ve ever worked with Django, you know that models are the backbone of any Django application. As a Python developer, I can confidently say that mastering Django models is essential to building scalable and maintainable web applications.

In this article, I’m going to walk you through how to create a model in Django from scratch. Whether you’re building a real estate listing site for US properties or a simple employee management system, understanding models will empower you to design your database schema efficiently.

Let’s get right in!

Django Model

In Django, a model is a Python class that represents a database table. Each attribute of the class corresponds to a database field. Django models provide an abstraction layer, so you don’t have to write raw SQL queries to interact with your database.

Think of models as the blueprint of your data. For example, if you’re creating a real estate app, you might have a Property model with fields like address, price, and listing_date.

Read Register User with OTP Verification in Django

How to Create a Model in Django: The Basics

Creating a model in Django is easy. You define a class in your app’s models.py file that inherits from django.db.models.Model then add fields as class attributes.

Here’s an example of a simple Property model for a US-based real estate application:

# myapp/models.py

from django.db import models

class Property(models.Model):
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=2)  # Use US state abbreviations
    zip_code = models.CharField(max_length=10)
    price = models.DecimalField(max_digits=12, decimal_places=2)
    listing_date = models.DateField(auto_now_add=True)
    is_available = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.address}, {self.city}, {self.state} {self.zip_code}"

Explanation of Fields:

  • CharField: Used for short text fields like address and city.
  • DecimalField: Perfect for currency values like price with fixed decimal places.
  • DateField: Stores dates; auto_now_add=True automatically sets the field to the current date when the object is created.
  • BooleanField: A simple True/False field to indicate availability.

Check out Create a Search Autocomplete with a Filter in Django

Step-by-Step: Add a Model to Your Django Project

Now, I will explain to you how to add a model to your Django project.

1. Create a Django App

If you haven’t already created an app, run:

python manage.py startapp myapp

2. Define Your Model

Add your model class to myapp/models.py as shown above.

3. Register the App

Make sure your app is registered in the project’s settings.py:

INSTALLED_APPS = [
    # other apps
    'myapp',
]

4. Create and Apply Migrations

Django uses migrations to propagate your model changes to the database.

Run:

python manage.py makemigrations myapp
python manage.py migrate

This will create the necessary database tables for your model.

5. Use the Model in Django Admin (Optional but Recommended)

To manage your data via Django’s admin interface, register your model in myapp/admin.py:

from django.contrib import admin
from .models import Property

admin.site.register(Property)

Now, when you run the development server and log into the admin panel, you can add, edit, and delete property listings easily.

I executed the above example code and added the screenshot below.

django create model
create model Django

Read Create a Card with a Button in Django

Method 2: Use Django’s AbstractBaseModel for Reusable Models

Sometimes, you want to create reusable models that can be inherited by other models. Django provides an abstract base class feature for this.

Here’s how you can create a base model for timestamp fields:

from django.db import models

class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now, you can inherit this in your Property model:

class Property(TimeStampedModel):
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=2)
    zip_code = models.CharField(max_length=10)
    price = models.DecimalField(max_digits=12, decimal_places=2)
    is_available = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.address}, {self.city}, {self.state} {self.zip_code}"

This approach adds created_at and updated_at fields automatically to all models inheriting from TimeStampedModel, saving you from repeating yourself.

Check out Create a Card with a Button in Django

Method 3: Use Choices for Field Validation

For fields like state you might want to restrict inputs to valid US state abbreviations. Django’s choices option is perfect for this.

Here’s how you can implement it:

class Property(models.Model):
    US_STATES = [
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        # Add all states here...
        ('NY', 'New York'),
        ('CA', 'California'),
        ('TX', 'Texas'),
        # ...
    ]

    address = models.CharField(max_length=255)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=2, choices=US_STATES)
    zip_code = models.CharField(max_length=10)
    price = models.DecimalField(max_digits=12, decimal_places=2)
    listing_date = models.DateField(auto_now_add=True)
    is_available = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.address}, {self.city}, {self.state} {self.zip_code}"

This way, Django will enforce that only valid state abbreviations are saved.

Read File Upload in Django

How to Query Your Django Models

Once your model is ready and migrated, you can interact with it via Django’s ORM in your views or shell.

For example, to get all available properties in California:

available_properties = Property.objects.filter(state='CA', is_available=True)

To create a new property:

new_property = Property.objects.create(
    address="123 Main St",
    city="Los Angeles",
    state="CA",
    zip_code="90001",
    price=750000.00,
    is_available=True
)

Creating models in Django is one of the most fundamental skills you need to build any web application. From defining simple fields to creating reusable abstract models and adding validation through choices, Django’s model system is powerful and flexible.

I’ve found that starting with a clear data schema and leveraging Django’s ORM saves a lot of time and headaches down the road. The examples above, especially with US-specific contexts like state choices and property listings, can be easily adapted to your projects.

If you’re new to Django, don’t hesitate to experiment with models and migrations. The more you practice, the more intuitive it becomes.

Happy coding!

Other Django articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.