Django Querying General Relationships
Overview
The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with data from various data sources such as SQLite, PostgreSQL, and MySQL.
Django allows us to add, delete, and modify objects, using an API called ORM. ORM stands for Object Relational Mapping. An object-relational mapper provides an object-oriented layer between relational databases and object-oriented programming languages without having to write SQL queries.
Introduction
Django includes an application content type that tracks all of the models installed in our project, allowing us to work with your models in a high-level, generic interface.
ContentType instances represent and store information about the models in our project, and new instances of ContentType are created automatically whenever new models are installed. As a result, ContentType model objects point to a specific table in our Django app. One of the ContentTypes' use cases is to create generic relationships between models.
Generic Relations is a type of relation supported by Django in which the relationship (foreign key) is not bound to a specific table instead it allows us to create a one-to-many relationship with any model we created. This can be useful if we want to implement a comment system or a like system that allows us to leave comments or likes on posts, images, and comments themselves.
Querying in Django
Let us consider an example. In the models.py file, we create the model into which we can enter the data.
After this, we will register the models we created in the admin.py file.
We need to run the following commands in the command prompt.
As we know in the above commands, 'makemigrations' is responsible for packing up 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 :
Now we can perform CRUD operations and queries.
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. So for retrieving the data 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 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 used get(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, to view the list of objects and the query we make on the webpage.
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 useget() 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
To delete a single object, at first we use the get() function and then delete() :
Querying General Relationships
A Django generic relationship is a type of relationship that allows you to create a one-to-many relationship with any model. Say we have a social media application in which we can like a post, comment, or page. So we create a model using a content type module and use it as a generic relation with the models' posts, comments, or pages. The generic relationship allows us to connect to a single model like with multiple models such as posts, comments, or pages.
Example of Querying General Relationships
So let us consider an example. Say we want to create a project in which we can comment on the books. We create a project name wick and applications named rec_com and record.
We first activate a virtual environment before creating the project and applications.
Now we register the applications in the settings.py file under the INSTALLED_APPS section. This section contains the list of the applications we created and also the preinstalled applications like django.contrib.contenttypes,django.contrib.admin, etc.
After doing this, we are supposed to make the models in both applications. Therefore in the application rec_com, we make a model Comment, which would help us post comments on any of the books in our database.
In the above code,
- We imported a generic foreign key (to connect the fields object_id and content_type) and content type.
- We create a model Comment.
- The following fields are the mandatory fields for a generic relation :
- content_type,
- object_id, and
- content_object.
- The content_type is a reference to the relation's content type or table.
- The object_id is used to store the row's id.
- The content_object is a direct reference to the object with which the comment entry is associated.
- The field text is used to enter the comment.
Now we register the app in the admin.py file.
We make a model Author and Book in the application record. In this step, we connected the model Comment (which would help us comment on the records of the model Book) to the model Book.
In the above code,
-
We imported the model comment from the rec_com application.
-
We imported Generic relations to use in our model.
-
We made two models Author and Book.
-
In the model Book, we created a field author to link the model Author.
-
We created a field com and connected the model Comment from app rec_com using Generic Relation. We again register the above models in the theadmin.pyfile,
Now we make migrations in the command prompt using the following,
Now we activate the shell.
In the shell, we import the models and then enter records and the comment.
Therefore, this is the way we can add comments to the books.
Conclusion
Hello Developer!! I am sure by now you must have learned about querying general relationships in Django. Let us summarize what we have learned so far
- An object-relational mapper provides an object-oriented layer between relational databases and object-oriented programming languages without having to write SQL queries.
- Django allows us to add, delete, modify, and query objects, using an API called ORM.
- CRUD operations include creating, retrieving, updating, and deleting data from the database model we create in Django.
- 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 updated view allows us to modify existing objects.
- Delete view helps us in deleting a record.
- Django Generic Relations are a type of relation supported by Django in which the relationship (foreign key) is not bound to a specific table rather it allows us to create a one-to-many relationship with any target model.