Django QuerySet and CRUD
This chapter delves into Django's database interactions and data storage mechanisms, focusing on the essential concept of the QuerySet.
Django QuerySet
A Query Set is a collection of data from a database. Query set allows us to get data easily, by allowing us to filter, create, order, etc. Let us take an example of a database table named Students, which we have already created.
ID | Name | Subjects |
---|---|---|
01 | Thomas | Physics |
02 | Jerry | Mathematics |
03 | Jacob | Biology |
04 | Robert | Computer Science |
05 | Betsy | Chemistry |
In views.py, we have a view called testing where we will test different queries. In the source code below, we use all() to get all the records and fields of the model Students. The object is placed in a variable known as mydata, it is sent to the template through the context object as mystudents, this will enable us to get the query set on the webpage.
Model Students contain 5 records, they are listed inside the Query Set as 5 objects.
Below is the source code of template.html, where we will be using mystudents object to generate content :
The output of the template.html is :
Django Shell
So to enter into the Django shell, the following command should be entered into the command prompt in the virtual environment :
This will lead us to an interactive console.
All Objects
There are some methods to get data from a model into a queryset :
-
all() :
It returns all the records of the database table. The source code for the same is given below :
The output is :
-
values_list() :
The values_list() returns only the column that is specified inside the syntax. The source code for the same is given below:The output is :
Create Objects
To create an object, at first we need to import the model Students
Thus for creating an object, use the following code
Filter Objects :
The filter() returns a query set with the records that match the conditions inside the syntax. The source code for the same is given below :
The output is :
Django also allows fetching filtered data based on multiple conditions, like AND and OR operations.
-
AND
We can get filtered data satisfying both queries mentioned. Refer to the example for demonstration. Say we want to retrieve a query set with the records that have field name as "Jerry" and field id as "2".The output it returns :
-
OR
We can also get filtered data that matches either of the query mentioned. An example is mentioned below. Say we want to get a query set with either the field name "Jacob" or field name "Robert".The output it returns :
-
Field Lookups :
Field lookups are keywords that represent specific SQL keywords. Say we want to get a query set with the records where the field name starts with the alphabet "J".The output it returns :
Some of the field lookup keywords are mentioned below :
Keywords Description Contains Contains the phrase icontains Contains the phrase but case sensitive endswith Ends with iendswith Ends with but case sensitive startswith Starts with istartswith Starts with but case sensitive
Ordering Objects
Django provides a feature to sort the query sets either alphabetically or in ascending and descending order, using order_by().
-
To sort the result alphabetically by name :
It returns the following :
-
To sort in descending order :
The results are by default sorted in ascending order based on the field name. To sort in descending order, we insert a '-' minus sign in front of the field name. Thus for sorting in reverse alphabetical order we add '-' in front of 'name'.The above code returns :
-
Multiple Order by :
To order based on more than one field, kindly consider the code below. Say we want a query set with the records in which the field name is sorted alphabetically and the field id is sorted in descending order.The above code returns :
Complex queries through method-chaining :
A query set can be combined with another query set by chaining them together,
The above code would return :
Django allows us to create database models and interact with them using an API called ORM. The primary goal of ORM is to send data between a database and application models. It represents a relationship between a database and a model. The main advantage of using Django ORM queries is that it speeds up and eliminates errors throughout the development process. It allows us to perform CRUD operations which stands for create, retrieve, update, and delete on our database model. CRUD operations include creating, retrieving, updating, and deleting data from the database model we create in Django. It helps us to keep a track of our data as well as to modify it.
Django CRUD (Create, Retrieve, Update, Delete) Function-Based Views
In the function-based view, we use a function in Python that receives the HttpRequest object as an argument and returns an HttpResponse Object in the form of HTML content, 404 error, XML document, etc. Function-based views are divided into four basic strategies (Create, Retrieve, Update, and Delete) CRUD.
Let us take an example of a function-based view.
In the models.py file, we create the model.
After creating the model we need to run the following commands in the command prompt.
As we know in the above commands, 'makemigrations' is responsible for packing the changes into individual migration files, and 'migrate' is responsible for applying those to our database.
Now to access Django ORM we write the following :
This leads us to an interactive Python console.
In the console, we create objects of the model as shown in the following example.
To see our model and its data in the admin panel we need to register our model in the admin.py file, present inside the folder of the app created.
We can check the created models here http://localhost:8000/admin/play/glitten/.
Now let us create the view function in the views.py file so that we can connect our HTML page with the view function we create.
In the code above, we imported our model Glitten, after creating a view 'list', we are using a dictionary named context with the title as keys and description as values.
Now a URL path is created to map the view. In the urls.py,
In the folder template, we create an HTML file named list.html which we linked in the view function built above.
We can check it at http://localhost:8000/.
Create View
We can create and add new records in the database table. Therefore, the following code is used to create and save an object in Model Glitten.
Retrieve View
Retrieving stands for getting the result of the search we make. We can either display the list of all the records or we can also get the query set with the records based on our search using filter(). So for retrieving all the records from the database, in Django, we write the following.
The output is a set of objects that match the query. Since we used the __str__() function for the model Glitten we see the output has the title displayed for all the objects.
-
The filter() is used to retrieve the data that exists already based on the condition we give in the command. For example, in the code below we used to filter(typeoftitle="vegetable") so the query set returned shows the record with typeoftitle as "vegetable".
-
The exclude() is used to retrieve the objects excluding or omitting the conditions we give in the command. In the code below we used, exclude(typeoftitle= "vegetable") and the output it returns does not contain any record with the typeoftitle as "vegetable".
-
The get() is used to retrieve a single object matching the conditions we give in the command. In the code below, we usedget(pk = 3), pk stands for the primary key. It uniquely identifies each row in the table. So here pk=3 returns the third object of the model. Django documentation declares that the primary key can be accessed using the keyword pk.
Detail View
Detail View is a view (logic) that allows a particular instance of a table from the database to be displayed with other details. For a detail view, we need a primary key which is the id for the identification of a particular instance of the model. Let us create a view in the views.py file.
In the above code,
- We have imported the model we created.
- We have created a class detailview.
- We have passed the request and id for the unique identification of a particular instance of the model.
- We have created a dictionary context, for data with field names as keys.
- We link the HTML page we will create and the dictionary context under the return render.
Now we are supposed to link the view to the URL path in the urls.py file,
In the above code,
- We have imported the detailview.
- In the URL path, we link the detailview and the id for each instance of a table.
We create a template named detailview.html in the folder template.
Update View
Django also allows us to modify existing objects. At first, we use get() to retrieve the single object which we want to modify then enter the data as in the code below a.title="lily" and save it using a.save().
Delete View
This is the delete operation of CRUD. To delete a single object from the records in the database table, at first we use the get() function and then delete() :
Conclusion
Hello developer!! I am sure by now you must have understood what Django query set cache is. Let us summarize what we have learned so far
- The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with data from various relational databases such as SQLite, PostgreSQL, and MySQL.
- A Query Set is data collection from a database.
- Query set allows us to get data easily, by allowing us to filter, create, order, etc.
- CRUD operations include creating, retrieving, updating, and deleting data from the database model we create in Django. It helps us to keep a track of our data as well as to modify it.
- Create view is used to create and add new records in the database table.
- The retrieve view is used for getting the result of the search we make.
- Detail View is a view (logic) that allows a particular instance of a table from the database to be displayed with other details.
- The update view allows us to modify existing objects.
- Delete view helps us in deleting a record.