In this Django Tutorial, we will be designing our first model in Django. Before we begin with the coding let's talk about what a model is. A model in Django contains fields and specific instructions how to handle data that we will be storing in the database. Each model in Django is a subclass of django.db.models.Model and each subclass of models.Model makes up a database table and each attribute of the subclass makes up a database field in Django.
Designing Our First Model In Django
Open up your favorite text editor and then open your Django project. Go into your lessons app and open the models.py file. This is where we will be designing our first database field in our Django project.
When you open the models.py file you will see the following.
from django.db import models
Create your models here.
On the first line you see from django.db import models. This line of code will import the Django module that will allow us to interact with models.Model class. We must keep this import statement in the file for our database to work.
Creating Our First Model Subclass
Now let's create our first subclass which will make a database table. We use a class to define the subclass of django.db.models.Model. Let's get started.
from django.db import models
Create your models here.
class Lesson(models.Model):
This line creates a class which is a subclass which will give us the ability to use the features of django.db module. Class indicates we want to use a construct called class. A class allows for a more organized way of coding. Then we add Lesson this is the name of our class. Since we are creating lessons with this model I call it Lesson because each data table will represent a single lesson. Then we provide models.Model argument to indicate we want this to be the subclass of models.
Creating Our Database Fields
Now that we have created our subclass which actually our database table we now create fields for our database table.
STATUS_CHOICES
from django.db import models
Create your models here.
class Lesson(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published')
)
We use the choice field here which we will actually initiate in our database shortly when it becomes an attribute of our status field. When working with a choices field we need to put the choices in an iterable object which can be a tuple or a list. I always use a tuple in this case. Then inside the tuple, we add our choices and they need to iterable as well and we will use a tuple again. Inside the second tuple, you see two words that are the exactly the same. The word on the left is the value the choice field will use and the one on the right is the human readable choice. When we use the choice field as an attribute I will be able to either set my lessons to draft which will not be displayed or set to publish where my lesson will be displayed to the users