Difference between revisions of "Python-Django/C2/Creating-Django-Models/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 37: Line 37:
 
|-
 
|-
 
|| Slide: Django App
 
|| Slide: Django App
|| * A '''Django project''' typically contains one or more '''apps'''
+
||  
 +
* A '''Django project''' typically contains one or more '''apps'''
 
* A '''Django app''' performs a particular task
 
* A '''Django app''' performs a particular task
 
* A '''Django app''' will have one or more '''models'''
 
* A '''Django app''' will have one or more '''models'''

Latest revision as of 06:05, 8 November 2019

Title of script: Creating Django Models

Keywords: Video tutorial, Django app, Django Model, Python Django, Django database migration

Visual cue Narration
Slide: Creating Django Models Hello and welcome to the spoken tutorial on “Creating Django Models”.
Slide: Learning Objectives In this tutorial, we will learn to:
  • Create a blog app
  • Initialize a Django app
  • Create a Django model and
  • Perform Database migration
Slide: System Requirements To record this tutorial, I am using
  • Ubuntu Linux 16.04 OS
  • Python 3.5
  • Python 3.4-venv or higher and
  • gedit Text Editor
Slide: Prerequisites To follow this tutorial, you need to know
  • How to create a Django project
  • If not, then please go through the pre-requisite tutorials in this series.
Slide: Django App
  • A Django project typically contains one or more apps
  • A Django app performs a particular task
  • A Django app will have one or more models
Slide: What is a Django Model? A Django model is a simple Python class.
  • A Model class represents a database table
  • A Model attribute represents a table field (each column in the table)
  • We write Django models in the models.py file
Slide: Creating Django Models for blog app In this tutorial, we will learn to create two models 'Blog' and 'Article' in the blog app.

The 'Blog' model will have 2 fields:

  • name and
  • created_on
Slide: Creating Django Models for blog app The 'Article' model will have 5 fields:
  • blog
  • created_on
  • title
  • body and
  • draft
Open a Terminal window Let us open the terminal by pressing Ctrl, Alt and T keys simultaneously on the keyboard.
[Terminal]

Type cd my-django & Press Enter

Using the cd command, go to the folder my hyphen django which we had created earlier.
[Terminal]

Type source myapp_env/bin/activate and press Enter

Let us activate the virtual environment myapp underscore env.

To do so type source <space> myapp underscore env slash bin slash activate

And press Enter.

[Terminal]

cd mysite & Press Enter

Now let us go to the mysite folder by typing

cd <space> mysite and press Enter.

Here onwards, please remember to press the Enter key after typing each command.
[Terminal]

Type python manage.py startapp blog and press Enter

For this demo, let us create a blogging app named 'blog'.

So type python <space> manage dot py <space> startapp <space> blog

Switch to Slide We have successfully created the blog app.

Let us now see the app file structure.

Slide:File structure

blog/

_init_.py

admin.py

apps.py

migrations/

_init_.py

models.py

tests.py

views.py

startproject command creates a project consisting of a file structure as shown here.
[Terminal] Switch back to the terminal.
[Terminal]

Type ls and press enter

Let us see the blog app directory in our project.

Type ls

[Terminal]

Highlight blog

We can see a directory named blog.
[Terminal]

Type ls blog and press Enter

Now, type ls <space> blog to list the files in the blog app.
[Terminal]

Point to the blog file structure in the terminal

We see the file structure of the blog app.

We will understand this structure in detail later in this series.

[Terminal]

Highlight

blog app

Now our project ‘mysite’ has to detect the blog app.

So, we should add the app name into settings.py file, which is present in the mysite directory.

[Terminal]

Type gedit mysite/settings.py & and press Enter

Let us open the settings.py file in any text editor.

I will be using gedit text editor.

Type gedit <space> mysite slash settings dot py <space> ampersand

[settings.py]

Point to INSTALLED_APPS

Locate the line INSTALLED UNDERSCORE APPS.

Let us add the app config line at the beginning of the INSTALLED UNDERSCORE APPS value.

[settings.py]

Type ‘blog.apps.BlogConfig’,

Type within single quotes blog dot apps dot BlogConfig comma

Now, the blog app will be detected by our project.

With this we have initialized the blog app.

Press Ctrl+S Press Ctrl and S keys to save the changes and close the file.
[Terminal]

Type gedit blog/models.py & and press Enter

Now, let us build models in this blog app.

Type gedit <space> blog slash models dot py <space> ampersand

[models.py]

Highlight from django.db import models

# Create your models here.

We are now in the models.py file.

Each model is a Python class that inherits from the django db models Model.

First let us add a model named Blog.

[models.py] Type:

class Blog(models.Model):

name = models.CharField(max_length=120)

created_on = models.DateTimeField(auto_now_add=True)

To add the model class with the database fields, type the code as shown here.
[models.py]

Highlight class

Here class is a special keyword that indicates that we are defining an object.
[models.py]

Highlight Blog

Blog is the name of our model.

We can give it any name, but we must avoid special characters and whitespaces.

[models.py]

Highlight (models.Model)

Our Blog model is inherited from the django db models Model.
[models.py]

Highlight name

Every attribute of the class is a field of the table.

A Field is used to describe the mapping of the model attributes to the database columns.

[models.py]

Highlight models.CharField

CharField defines the text with a limited number of characters.
[models.py]

Highlight (max_length=120)

The max underscore length is enforced at the database level and in Django’s validation.

Here, the character length is one hundred and twenty.

[models.py]

Highlight models.DateTimeField

Django’s DateTimeField is a very useful argument for automatically managing the date and time.
[models.py]

Highlight (auto_now_add=True)

The auto underscore now underscore add will set the very first creation time of the object.
[models.py] Type:

class Article(models.Model):

blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

created_on = models.DateTimeField(auto_now_add=True)

title = models.CharField(max_length=120)

body = models.TextField()

draft = models.BooleanField(default=False)

Now, let us add the other model Article.

Type the code as shown here.

[models.py]

Highlight models.ForeignKey

Here models dot ForeignKey is a link to another model.

This will create an object that has a many-to-one relationship.

[models.py]

Highlight (Blog, on_delete=models.CASCADE)

A many-to-one relationship requires two positional arguments.

The class to which the model is related and the on underscore delete option.

[models.py]

Highlight

on_delete=models.CASCADE

on underscore delete argument is required when adding a ForeignKey field.

In SQL there is constraint named ON DELETE CASCADE.

Here Django reproduces the same behaviour.

[models.py]

Highlight

CASCADE

When the referenced object is deleted, it also deletes the objects that have references to it.
[models.py]

Highlight

models.DateTimeField(auto_now_add=True)

Similar to the Blog Model, created underscore on creates the DateTimeField for the Article model.
[models.py]

Highlight

models.CharField

Next, we are inserting the Article’s title which is a character type Field.
[models.py]


Highlight

models.TextField()

This is to accommodate a long text that does not require a text limit to be specified.
[models.py]


Highlight

models.BooleanField(default=False)

The next field contains either True or False.


Here we have set the default value as False.

Save the code Ctrl + S This is how we have added our Models Blog and Article.

Now, save and close the file.

Clear the terminal

[Terminal]

Type python manage.py --help

The next step is the migration of our Model to the database.

For help, type

python <space> manage dot py <space> hyphen hyphen help

[Terminal]

Point to the shell prompt

Here, we can see the list of available commands and options.
[Terminal]

Highlight

makemigrations

makemigrations will create new migrations based on the changes in your model.
[Terminal]


Highlight

migrate

migrate applies the changes noted during the makemigrations phase.
[Terminal] Clear


Type python manage.py migrate and press Enter

Clear the terminal.

Now, type


python <space> manage dot py <space> migrate

[Terminal]

(Running migrations)

The migrate command looks at the INSTALLED_APPS setting.

It will create a database for all the existing apps in the settings dot py file.

[Terminal]

Highlight

Apply all migrations:

admin, auth, contenttypes, session

The migrate command will only run migrations for the apps in INSTALLED UNDERSCORE APPS.
[Terminal]

Type

less mysite/settings.py

Let us view the settings dot py file without opening it in the editor.

To do so, type less <space> mysite slash settings dot py

[Terminal]

Highlight INSTALLED_APPS

Scroll down.

Except for the blog app, all other apps have been migrated.

Let us understand this in detail.

[Terminal] Press q Press q to exit from the less command.
[Terminal]

Type ls blog/migrations and press Enter

The migration files for each app will be available in the migrations folder inside that app.

Let us now check the migrations folder in the blog app.

Type ls <space> blog slash migrations

[Terminal] Highlight output We only see the init dot py file and there are no migration files.
[Terminal]

Type python manage.py makemigrations blog and press Enter

Let’s run the makemigrations command for our blog app.

Type python <space> manage dot py <space> makemigrations <space> blog

[Terminal]

Point to shell prompt

Highlight

Migrations for 'blog':

blog/migrations/0001_initial.py

- Create model Article

- Create model Blog

- Add field blog to article

By running makemigrations, we are telling Django that we have made some changes to our models.


Django will create the initial migrations files based upon your current models.

[Terminal]

ls blog/migrations/

Let us check the migrations folder again.

Type ls <space> blog slash migrations

[Terminal]

Highlight

001_initial.py

Now we can see that 001 underscore initial dot py file has been created.

makemigrations will create a new migration file when there are changes in the module.

[Terminal]

Type python manage.py migrate and press Enter

Now, run migrate again to create those model tables in your database.
[Terminal]

Point to the output on the terminal

Highlight

Operations to perform:

Apply all migrations: admin, auth, blog, contenttypes, sessions

Running migrations:

Applying blog.0001_initial... OK

Now, we see the command line output for migrate.

The migrate command takes all the migrations that haven’t been applied.

[Terminal]

Type ls and press Enter

Now type ls and press Enter.
[Terminal]

Highlight db.sqlite3

We can see that Django automatically created an SQLite database file, by default.

This is because in settings, it is specified by default.

[Terminal]

Type less mysite/settings.py

Let us check this.

Type less mysite slash settings dot py

[Terminal]

Highlight DATABASES

Highlight default

Highlight ENGINE sqlite3

Highlight NAME db.sqlite3

Scroll down.

Under DATABASE, we can see

  • default connection
  • ENGINE as sqlite3
  • NAME as db dot sqlite3
[Terminal]

Press q

Press q to exit from the less command.
We will understand migrations better in the upcoming tutorials of this series.

So far, we have learnt to create models within the blog web application.

Type deactivate [Enter] Let us deactivate the virtual environment now.


To do so, type deactivate and press Enter.

With this, we come to the end of this tutorial.

Let us summarize.

Slide: Summary In this tutorial, we have learnt to
  • Create a blog app
  • Initialize a Django app
  • Create a Django Model and
  • Perform Database migration
Slide: Assignment Assignment,
  • Create models under the blog app in demo_project
  • Perform database migrations for the models created
Slide: About Spoken Tutorial project The video at the following link summarises the Spoken Tutorial project.

Please download and watch it.

Slide: Spoken Tutorial workshops The Spoken Tutorial Project team conducts workshops and gives certificates.

For more details, please write to us.

Slide: Forum for specific questions: Please post your timed queries in this Forum.
Slide: FOSSEE to answer questions Please post your general or technical questions in this Forum.
Slide: Acknowledgement Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.

More information on this mission is available at this link.

Slide: Thanks Slide This script has been contributed by Thiagarajar College of Engineering and the FOSSEE Project, IIT Bombay.

The video has been recorded by Praveen from Spoken Tutorial Project, IIT Bombay.

Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Pravin1389