Setting up a Django app model

After you’ve started your Django server and first app, you now need to setup your model for the app.

A model is just a class used by Django to operate your app. Open the models.py file located in the root directory of your app to begin editing.

from django.db import models

# Create your models here.

Under the comment, “Create your models here.” you add classes for your app. For example, let’s model a hamburger restaurant. We’ll create a model of a specialty burger (e.g. Avocado Cream) that stores the name and when it was added to the menu.

class Burger(models.Model):
    '''A model for a burger'''
    name = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        '''Return the name of the burger'''
        return self.name

We can also add a model for toppings that will hold a description of the burger’s toppings (avacado and cream cheese). The ForeignKey tells Django that this model is linked to another model (Burger) in the database.

class Topping(models.Model):
    '''A model for toppings'''
    burger = models.ForeignKey(Burger, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

    def __str__(self):
        return f'{self.name}'

Now that we have an app and a model, we have to tell Django to include our app in the webserver by activating the models. Open the settings.py file located in the root directory of your project.

Scroll down to “INSTALLED_APPS” and modify it like below. Replace ‘burger_joint’ with the name of your project.

INSTALLED_APPS = [
    # My Apps
    'burgers', 
    # Django Default Apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Now we need to tell Django to update the database to include items for our two models. Run the following commands to revise the database, where “burgers” is the name of your app.

python manage.py makemigrations burgers
python manage.py migrate

The first command tells Django what needs added to the database, the second command adds them to the database.

You’ve now setup your basic models for your app! Head to my next post in this series to learn how to setup a Django super user.

John

Leave a Reply

Your email address will not be published. Required fields are marked *