Part 6 - Basic operations on Models In Django

November 17th, 2020 6 min read

This is part of the series Django For Beginners we are going to see about apps in app and we will see about models in django in this part.

In this post we are going to learn about the basics of queries in django. When we use django we do not need to write SQL Queries it is done by django itself, we write super user friendly syntax for the queries ,

Let’s see we want to get all the objects in a model ( note each model is a table, it may be more depending on the type of relation used while creating it ), let the schema of this model be simple it will be as follows,

from django.db import models

class Book(models.Model):
	title		= models.CharField(max_length=250)
	createdAt   = models.DateTimeField(default=timezone.now)
	description = models.TextField()
	orders      = models.PositiveItegerField(default=0)

Now to get it all we use the following syntax,

allBooks = Book.objects.all()

and that’s it will return all the books of QueryList form.

How to run Queries in Django ?

I should have told it first I know but I told it now because you should understand how easy it is to write queries in django. Now let’s see how to run them,

There are two ways,

  1. Interactive Way ( in command line ).
  2. In any python file.

Interactive Way

To use it interactively just go to your root directory of your django project and type the following command to start the interactive console,

python manage.py shell

It will start the interactive console from which you can import any model in the project, you can access all of the project files. Also you can also import normal python libraries.

Regular Way

You can import models to any file in the project and can use it as per your will and in later part of this series we are going to use in this way in views.py to write views for our website.


Now let’s see the basic operations on models,,

To Create New Model Object

To create new model object we first import it and then we use create method which is build in model on it and create it. Let me show a example to you,

from myapp.models import Book

newBook = Book.objects.create(title="Harry Potter - Some Part", description="Don't you know it ?")
newBook.save()

As you may have seen that creating models is simple damn simple. We just need to pass values in objects.create method of that model and store it in variable and than use save method on it. It is as simple as it could get.

You may have seen that I have not passed certain parameters, such as createdAt and orders, because we have provided default values to it. But we can also pass it. Let me show you how,

from myapp.models import Book
from datetime import datetime
from random import randint

currentDateTime = datetime.now()
orders = randint(0,10)

newBook = Book.objects.create(title="Harry Potter - Some Part", description="Don't you know it ?", createdOn=currentDateTime, orders=orders)
newBook.save()

This is how it is done. You may have seen that I have passed createdOn in third place but while creating model it was in 2^nd^ place I did it to show that order in which you pass these keyword arguments doesn’t matter.

Query The Object

Now comes the part of querying the model, here I will cover basics as querying is a very big topic, with the part I cover here would e more than enough for many project , at least in the beginning. Now let’s start,

For each time I will not write import statement for the model, you can copy it from here if you would like to do it,

from myapp.models import Book
Getting All Objects
allBooks = Book.objects.all()

We can use objects.all() method on a model to get all of the objects in the model.

Getting Objects By The Values of their Fields
allBooks = Book.objects.filter(title="Harry Potter - Some Part")

We can use objects.fiter() method on a model to filter objects in the model. We can pass keyword argument like as I have done above to filter it according to your needs.

Now what I have done above is that I have filtered objects which have Harry Potter - Some Part in their title no other objects will be available in the results even if it differs be a space ( ).

Using Like Queries On Objects
allBooks = Book.objects.filter(title__contains="Harry Potter - Some Part")

We attach __contanins to the end of the name of the filed we want it to run like query on. l

Note : __contanins is case-sensitive, which means case of query matters. To use non-case-sensitive queries use __icontains note it has i in the beginning.

For those of you who don’t what like query is it is just that it will search for the records in the database which contains title similar to our given title.

Queries in Django is a big topic and deserves a blog post or two of its own,but if you want to learn more about queries in django I would highly suggest you to checkout Django’s documentation on queries.

Editing Models

Editing models is as simple as creating it, let’s see this in an example,

from myapp.models import Book

book = Book.objects.get(id=1)
book.title
# Response -> Some Cool Title
book.title = "Some Cool Title - Imporoved"
book.save()

Here we get object by running get query . And Now to edit model we edit it like a object ( sort of ) by storing the get query in a variable and then to access the property of the model we use the following syntax modelvar.field_name , and as you can see above we put a = sign and assign it the value we want to assign, and then use save() method on this variable .

Deleting Models

Deleting models is simplest by far, what we do is that we just get the model and use delete() method on it. Let’s see an example,

from myapp.models import Book

book = Book.objects.get(id=1)
book.delete()

That’s it nothing else.

And guys as you have reached so far I want to ask you for a favor, that can you please share this post as this is small new blog it will help a ton to me. Also and more importantly thanks for reading till here.

Hope you like it. In upcoming blog probably in a week I am going to cover about queries in django, so if your are interested you can bookmark my site.


You may also like: