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 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'''

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'{}'

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 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.

    # My Apps
    # Django Default Apps

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 makemigrations burgers
python 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.


Leave a Reply

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