Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Models – A Complete Beginner’s Guide

Django Models

Django models are classes that represent a table or collection in our Database. It contains all the information regarding the table. These models are stored together in Django in a file models.py in our Django App.

There can be many different models for different DB containing different information like User DB, Book DB, or any other table required by the web application.

Basic Structure of Django Models

class Modelname(models.Model):
	'''A class representing a model derived from Model class'''
    #Fields
    Field_name = models.CharField(max_length = , hepl_text = , choices = , Null etc)

    #Metadata
    class Meta:
        Ordering = [‘field_name’]

    #Methods
    def __str__(self):
	    return '<readable_name>'

1. Fields in a Model

A particular model can have any number of fields, these represent the various attributes of the database table.

There can be many different types of fields

  • CharField
  • IntegerValue
  • Email

These fields can also take arguments like 

  1. max_length – The max number of characters possible.
  2. Primary key – This tells Django that this field is going to be unique for all the entries.
  3. Foreign key – This is used to connect one model with another model.
  4. NULL – If true, will convert empty fields into null value, char field take them as empty strings
  5. Choices – If the field has to be only one of the given options(like a option box)
  6. Blank – If true, the field can be allowed to be blank,otherwise has to be filled.

2. Model Metadata

This metadata has various features; one of the most important being the ordering. It allows you to show the responses in a particular order in the database when you give a request for that. 

The syntax is as follows

ordering ['<Name>']

This tells models to arrange the elements in the DB in the order according to the <name> ie could be alphabetical if <name> is CharField or could be Numerical ascending order if its IntergerField etc.

if the syntax is used with “-“ sign, this means that the ordering should be in the reverse order

ordering [-'<name>']

3. Methods in Django Models

These are used for better client interface, that is for better presentation etc.

__str__ , for example, tells you what to show you (like a short name) in the admin site for each particular element in the database. (instead of showing the full information)

Now let us make a project of Books, having the following information:

  • A homepage with information about all the books
  • Webpages containing the information of each book. (we saw that in Django URL mapping)

For that, make an App named books using the knowledge gained in the previous articles. 

1. Creating Our First Django Model

In the books/models.py let’s make a model DB having Title, Price, and Genre as attributes with metadata ordering of Title.

BookModel
BookModel

Now to we need to create this table in our database. By default, Django uses the SQLite database engine. For now, we will use this DB itself.

You can check the DB you are using from the settings.py file under DATABASES

settings.py
Settings.py

2. Creating a Table in the Database

To create the table first we need to apply migrations. Write the code below in the shell

python manage.py migrate
python manage.py makemigrations <app_name>
Python manage.py sqlmigrate <app_name> 0001

And once again, run:

Python manage.py migrate

The output will indicate the successful creation of your database.

Your model table is ready in SQLite. Note that whenever we make changes to our model we need to repeat the steps above in order to make changes in the table in the DB as well.

Now we will learn to get/add data in to the DB

Retrieving information from DB

Now first we need to open python shell inside the directory, using the command:

python manage.py shell

Hence now we will have the python console appearing in the shell. We need to import the model table in order to add/retrieve information from it.

The syntax to import table is:

from <app_name>.models import <model_name>

In my case it will be like this

Python Shell
Python Shell

1. Get all objects from a rable

For this we use the syntax

<model_name>.objects.all()

Hence my code will be :

BookModel.objects.all()

2. Add information into the table

To add the information, the syntax is similar to object-oriented python syntax. Here first we create a class object with the model name and then add the attributes required.

To create an object, the syntax is:

A = <model_name>()

Example:

A.Title = "Harry Potter"
A.Price = 120
A.Genre = "Fantasy Fiction" 
A.save()

Thus we have entered our first book information. Similarly, I will add a few more.

Addition To DB
Addition To DB

3. Filtering records from the DB

To filter records from a Django model Database, we run:

<Model_name>.objects.filter(Title =”<Title_Element>”)

Hence for example if I filter out all the Books with genre say Fiction, then

Filter
Filter

4. Getting complete information about an element

Note: When we use a filter, we get the element in the short form (in a way as described by def __str__) But if we want full information about an element we use this method

<model_name>.objects.get(Title = <"title_element">)

Here we can get all the information including the title. price, genre.

That is when we use

a = BookModel.objects.get(title = "Ghostbuster")

Then all the information is stored as an object, so if we implement the following then it will print the corresponding values.

a.title()
a.price()
a.genre()

5. Delete an row element from DB

To delete a particular element, we use the syntax .delete()

from books.models import BookModel
a =BookModel.objects.get(title="<book_name">)
a.delete()

Connecting to model DB via views.py

Now we will learn how to take up information from the DB and then show it on our webpage.

In Views.py add the code:

def BookView(request):
    books = BookModel.objects.all()

    html = ''
    for book in books:
        var = f'<li> {book.title} </li><br>'
        html = html + var
    return HttpResponse(html,status = 200)

Now from the code, u can understand that we basically retrieved all the DB info into variable books and then we started a loop to get each element from the DB and show on the webpage as HTML.

We must also provide the endpoint (Books/) for this View. Try it on your own from the knowledge gained from the Django-URL mapping article

URL mapping
URL mapping

Now for the web page (books/<Title_name>). Look at the code below to understand better.

BookIDView
BookIDView

The code is simple; we are just taking all the information about the book_name using Get and then showing it on the webpage as HTML

Here we have retrieved specific information from the DB and then displaying it on the Web page. Let us see how the urls.py file looks like for this View.

URL mapping - BookIDView
URL mapping – BookIDView

Now we will run the server and see if its working

Runserver
Runserver

Browser page for books/ webpage

Browserbooks 1024x583 1
Browser (books/)

Browser page for books/<Title_name> webpage

Browser Ghostbuster
Browser (books/Ghostbuster)
BrowserHarry Potter 1024x583 1
Browser (books/Harry Potter)

Connecting to other models using Foreign Key

A foreign key(FK) is used to link up two databases that are using some common information. This helps to keep our Databases clean and also ensures we don’t have to enter the same information again and again.

Now in our books app, let us make an Author Model Table and also add the Author_id field in our Book Model. Now note that Several books might have the same Author, so Author_id will act as the Foreign Key in our BookModel.

Using FK, we can search for various books written by a particular author. Also if an Author deletes his account, then all his books will also be deleted automatically thereby reducing the work of deleting them manually from the BookModel.

You might get confused a bit in the starting but after repeated practice, it will start making sense. So Don’t Worry !!

AuthorModel
AuthorModel

Now we can add the Author field in the BookModel.

Authorfield django models
Author_id Field

We have to run migrations for our new AuthorModel. Also Note: we have to run the shellcodes(migrations) as mentioned earlier since we changed our BookModel DB.

Migrations
Migrations

We already had some information in the database without the Author field. So Django asks to enter a default value in the author_id field for them.

It is preferred to delete all the earlier elements before applying the migrations (to change the table) using .delete()

We can now add information to Author DB in the same way we added Book Information.

Author DB
Author DB

Also as practice, try to create an Author View yourself similar to the BookView.

We have now learnt to enter data, into tables through shell, but this is not the most efficient way to add data. The easiest way is to add data through admin site. We will learn how to do that in the next article.

Also from the admin site, you will get more information about the working of this whole FK, and how Author DB and Model DB are linked with each other through FK.

Conclusion

And thats it, we have reached the end of the article. In the next article, we will learn about the admin site interface and then see the utility of FK in a better way. Keep coding !!