Django — Creating Your First Model

Thomas
2 min readDec 11, 2020

Models are a core pillar of the Django web framework. They contain the essential fields and data that you will be saving into the database for storage.

You will find the models.py file inside the application folder of your project. This is what we will use to write our models.

Let’s create your first model.

  1. Ensure you have models imported from django.db
  2. Create a class with an appropriate name (i.e. Customer)
  3. Define each data point that you wish to include for each Customer. The field classification in our example is commonly used (characters) and requires you to define the maximum length.
  4. Save the file and make it a consistent habit to migrate the changes to the database via these 2 commands (in your command prompt):
1. python manage.py makemigrations         * Important2. python manage.py migrate                * Important

Your models.py file should look similar to this:

from django.db import models                    ESSENTIAL IMPORT


class Customer(models.Model): MODEL NAME
name = models.CharField(max_length=20) DATA FIELDS
email = models.CharField(max_length=20)

There are numerous field types to use in your models depending on the data you wish to collect. Commonly used field types are displayed below:

AutoField                EmailField
BooleanField FloatField
CharField ImageField
DateTimeField IntegerField
DecimalField TextField

The changes have now been made to the database and you’re almost there. Next, open the settings.py file, import the model and then register it to the admin component of your website. You will now be able to view and make changes in your admin panel.

~ settings.py from django.contrib import admin
from .models import Customer

admin.site.register(Customer)

In regards to the admin panel it can also be helpful to return an __str__ function for each model. Each model item will then be labelled and more organised (particularly with larger data sets).

class Customer(models.Model):name = models.CharField(max_length=20)
email = models.CharField(max_length=20)

def __str__(self):
return self.name

After creating several entries each name will now clearly display in your admin page.

That’s it! Creating models is a core pillar of Django and can become much more advanced depending on the complexity of your database and how models relate to each other.

Further help can be found in the official documentation here.

--

--