Difference between revisions of "Python-Django/C2/Creating-Django-Models/English"
Pravin1389 (Talk | contribs) (Created page with "'''Title of script:''' Creating Django Models '''Keywords:''' Video tutorial, Django app, Django Model, Python Django, Django database migration {| border=1 |- || Visual cue...") |
Nancyvarkey (Talk | contribs) |
||
(One intermediate revision by the same user not shown) | |||
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''' | ||
Line 96: | Line 97: | ||
Type python manage.py startapp blog and press Enter | Type python manage.py startapp blog and press Enter | ||
− | || For this demo, let us create a '''blogging app''' named ''''blog''''. | + | || For this demo, let us create a '''blogging app''' named ''''blog''''. |
So type '''python <space> manage dot py <space> startapp <space> blog''' | So type '''python <space> manage dot py <space> startapp <space> blog''' | ||
Line 124: | Line 125: | ||
views.py | views.py | ||
− | || startproject command creates a project consisting of a file structure as shown here | + | || '''startproject''' command creates a '''project''' consisting of a file structure as shown here. |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
− | || Switch back to '''terminal.''' | + | || Switch back to the '''terminal.''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 175: | Line 176: | ||
Point to INSTALLED_APPS | Point to INSTALLED_APPS | ||
− | || Locate the line ''' | + | || Locate the line '''INSTALLED UNDERSCORE APPS.''' |
− | Let us add the '''app config '''line at the beginning of the ''' | + | Let us add the '''app config '''line at the beginning of the '''INSTALLED UNDERSCORE APPS''' value. |
|- | |- | ||
|| [settings.py] | || [settings.py] | ||
Line 266: | Line 267: | ||
Highlight (auto_now_add=True) | Highlight (auto_now_add=True) | ||
− | || The ''' | + | || The '''auto underscore now underscore add''' will set the very first creation time of the object. |
|- | |- | ||
|| [models.py] Type: | || [models.py] Type: | ||
Line 288: | Line 289: | ||
Highlight models.ForeignKey | Highlight models.ForeignKey | ||
− | || Here '''models | + | || Here '''models dot ForeignKey''' is a link to another '''model.''' |
This will create an '''object''' that has a many-to-one relationship. | This will create an '''object''' that has a many-to-one relationship. | ||
Line 297: | Line 298: | ||
|| A many-to-one relationship requires two positional '''arguments.''' | || A many-to-one relationship requires two positional '''arguments.''' | ||
− | The '''class''' to which the '''model''' is related and the ''' | + | The '''class''' to which the '''model''' is related and the '''on underscore delete''' option. |
|- | |- | ||
|| [models.py] | || [models.py] | ||
Line 304: | Line 305: | ||
on_delete=models.CASCADE | on_delete=models.CASCADE | ||
− | || ''' | + | || '''on underscore delete argument''' is required when adding a '''ForeignKey field.''' |
In''' SQL '''there is constraint named '''ON DELETE CASCADE.''' | In''' SQL '''there is constraint named '''ON DELETE CASCADE.''' | ||
Line 322: | Line 323: | ||
models.DateTimeField(auto_now_add=True) | models.DateTimeField(auto_now_add=True) | ||
− | || Similar to the '''Blog Model''', ''' | + | || Similar to the '''Blog Model''', '''created underscore on''' creates the '''DateTimeField''' for the '''Article''' '''model'''. |
|- | |- | ||
|| [models.py] | || [models.py] | ||
Line 366: | Line 367: | ||
For '''help''', type | For '''help''', type | ||
− | '''python manage dot py <space> hyphen hyphen help''' | + | '''python <space> manage dot py <space> hyphen hyphen help''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 388: | Line 389: | ||
|| '''migrate''' applies the changes noted during the '''makemigrations''' phase. | || '''migrate''' applies the changes noted during the '''makemigrations''' phase. | ||
|- | |- | ||
− | || [Terminal] | + | || [Terminal] Clear |
Type python manage.py migrate and press Enter | Type python manage.py migrate and press Enter | ||
− | || Now, type | + | || Clear the '''terminal'''. |
+ | |||
+ | Now, type | ||
Line 412: | Line 415: | ||
admin, auth, contenttypes, session | admin, auth, contenttypes, session | ||
− | || The '''migrate command''' will only run migrations for the '''apps '''in ''' | + | || The '''migrate command''' will only run migrations for the '''apps '''in '''INSTALLED UNDERSCORE APPS.''' |
|- | |- | ||
Line 472: | Line 475: | ||
- Add field blog to article | - Add field blog to article | ||
|| By running '''makemigrations''', we are telling '''Django''' that we have made some changes to our '''models.''' | || 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.''' | '''Django''' will create the initial migrations files based upon your current '''models.''' | ||
Line 480: | Line 484: | ||
|| Let us check the '''migrations''' folder again. | || Let us check the '''migrations''' folder again. | ||
− | Type '''ls blog slash migrations | + | Type '''ls <space> blog slash migrations''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 487: | Line 491: | ||
001_initial.py | 001_initial.py | ||
− | || Now we can see that ''' | + | || 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 ''' | + | '''makemigrations''' will create a new '''migration''' file when there are changes in the '''module.''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 496: | Line 500: | ||
|| Now, run '''migrate''' again to create those '''model tables '''in your '''database.''' | || Now, run '''migrate''' again to create those '''model tables '''in your '''database.''' | ||
− | |||
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 511: | Line 514: | ||
Applying blog.0001_initial... OK | Applying blog.0001_initial... OK | ||
− | || Now, we see the command line output for '''migrate.''' | + | || Now, we see the '''command line''' output for '''migrate.''' |
The '''migrate command''' takes all the migrations that haven’t been applied. | The '''migrate command''' takes all the migrations that haven’t been applied. | ||
Line 524: | Line 527: | ||
Highlight db.sqlite3 | Highlight db.sqlite3 | ||
− | || We can see that '''Django''' automatically created an '''SQLite | + | || We can see that '''Django''' automatically created an '''SQLite database''' file, by default. |
− | This is because in '''settings '''it is specified by default. | + | This is because in '''settings, '''it is specified by default. |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 547: | Line 550: | ||
Under '''DATABASE, '''we can see | Under '''DATABASE, '''we can see | ||
− | '''default connection''' | + | *'''default connection''' |
− | '''ENGINE '''as''' sqlite3''' | + | *'''ENGINE '''as''' sqlite3''' |
− | '''NAME '''as''' db dot sqlite3''' | + | *'''NAME '''as''' db dot sqlite3''' |
|- | |- | ||
|| [Terminal] | || [Terminal] | ||
Line 561: | Line 564: | ||
|| We will understand '''migrations''' better in the upcoming tutorials of this series. | || We will understand '''migrations''' better in the upcoming tutorials of this series. | ||
− | So | + | So far, we have learnt to create '''models''' within the '''blog web application'''. |
|- | |- | ||
|| Type deactivate [Enter] | || Type deactivate [Enter] | ||
− | || Let us deactivate the '''virtual environment '''now | + | || Let us deactivate the '''virtual environment '''now. |
+ | |||
To do so, type '''deactivate''' and press '''Enter'''. | To do so, type '''deactivate''' and press '''Enter'''. |
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:
|
Slide: System Requirements | To record this tutorial, I am using
|
Slide: Prerequisites | To follow this tutorial, you need to know
|
Slide: Django App |
|
Slide: What is a Django Model? | A Django model is a simple Python class.
|
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:
|
Slide: Creating Django Models for blog app | The 'Article' model will have 5 fields:
|
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]
models.TextField() |
This is to accommodate a long text that does not require a text limit to be specified. |
[models.py]
models.BooleanField(default=False) |
The next field contains either True or 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]
migrate |
migrate applies the changes noted during the makemigrations phase. |
[Terminal] Clear
|
Clear the terminal.
Now, type
|
[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.
|
[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
|
[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.
|
With this, we come to the end of this tutorial.
Let us summarize. | |
Slide: Summary | In this tutorial, we have learnt to
|
Slide: Assignment | Assignment,
|
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. |