Django model is a powerful source of information and exposes data stored within a single database table.

But what exactly does that mean?

Well, the simplest way of conceptualizing a model is to consider it a blueprint for storing information.

To demonstrate this powerful built-in feature of Django, let’s create a model that lists popular movies. First we will create the model and its fields, then we will login to the Django administration site and fill in the fields with information on different movies, and finally we will render the code using a for loop.

Create a model

env > mysite > main > models.py

from django.db import models

# Create your models here.

class Movie(models.Model):
	movie_title = models.CharField(max_length=150)
	release_year = models.IntegerField()
	director = models.CharField(max_length=100)
	movie_plot = models.TextField()

	def __str__(self):
		return self.movie_title

Start by opening the models.py file in the app directory folder. Add the class Movie inherits (models.Model) just below the comment. Next, we need to specify all of the information we want to list under each movie we add to our project.

First, add a field for the movie’s title. This field is a CharField or character field that takes in a maximum of 150 characters of text. Next, add an IntegerField for the release year. Let’s also add a field for the director’s name. The last field we will add is for the movie’s plot. This field is a TextField that allows paragraph text submissions.

Before we move on, let’s add a function that returns the movie’s title as the display name. If you forget to add this function it will list as Movie object (1), Movie object (2) and so on, making it hard to know which object corresponds to a particular movie.

Be sure to save the file.

Make migrations to create the model

macOS Terminal

(env)User-Macbook:mysite user$ python3 manage.py makemigrations
Migrations for 'main':
  main\migrations\0001_initial.py
    - Create model Movie

(env)User-Macbook:mysite user$
____________________________________________________________________
Windows Command Prompt
(env) C:\Users\Owner\Desktop\Code\env\mysite>py manage.py makemigrations
Migrations for 'main':
  main\migrations\0001_initial.py
    - Create model Movie

(env) C:\Users\Owner\Desktop\Code\env\mysite>

In order to use the model in the Django admin, we need to makemigrations and create the model that maps to single database table.

#django #python #python-programming #django-models #web-development

How to use Django Models
2.00 GEEK