Experimenting with Django

Bismita Guha
AnitaB.org Open Source
2 min readJul 28, 2020

Here, I am describing just a few interesting changes that can be done to reduce the code being written in views.

Generalising code

In my GSoC project, I had to implement create and list functions with multiple models and serializer. So I wrote easy functions, rather than complicating the code to include loops with conditional statements.

This is a file from my code, where I have returned a dictionary that has the model and serializer based on the data type passed in the function.

Related Name

Django related name might seem like not a necessary feature but it actually proves to be really helpful to access the models through reverse relations. You can find the details in this documentation:

Now instead of making SQL queries to multiple tables which are related we can directly access them, in one line. For example look at this relation:

Many to Many Relation

Suppose we need to filter objects in the Answer model, based on some feature of the Form Feedback, i.e, user_id and form_id. The basic process would be first filtering the Form Feedback model, and retrieve the answers list and then make a query to the Answers model.

A simpler method, considering the related name of the answers (M2M) in the Form Feedback model is form_answers, will be:

queryset = Answer.objects.filter(form_answers__form_id=form_id, form_answers__user_id=user.id)

Not only one model, but this can be extended to multiple related models. So it’s just a double underscore which makes your job easier, and you can easily relate the queries.

Enjoy writing Django!!!

--

--