Better Django: Chapter 1
- Achieve more with less code.
Table of contents
Having worked with Django for a significant number of years, I've examined various Django codebases and found cases where 10 lines of code can be condensed to around 4-5 lines while still maintaining or even improving effectiveness. This article aims to show you how you can do more with less code.
"The quantity of code on your screen doesn't determine your proficiency as a developer."
Object Retrieval
Let's take an example:
I want to write a program to find a BlogPost with the given id & raise a 404 error if not found. Instead of using the conventional try/except blocks, you can make use of your get_object_or_404
module from django shortcuts.
get_object_or_404
function is included in Django's standard library, requiring no additional installation when you install Django itself.from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import BlogPost
from .serializers import BlogPostSerializer
class ProductDetailView(APIView):
def get(self, request, pk):
blogpost = get_object_or_404(BlogPost, pk=pk)
serializer = BlogPostSerializer(blogpost)
return Response(serializer.data)
get_object_or_404
module takes in 2 arguments, the model name from which you want to fetch an object. This could also be a Django QuerySet
instance, allowing for more refined searches and the filter criteria to filter the query to the specific object you want to retrieve. These are passed as keyword arguments. For a model class, you might use field lookups like pk=pk_value
or slug=slug_value
, where pk_value
and slug_value
are the specific primary key or slug you're querying for.In situations where you aim to present a customized message rather than solely triggering a 404 error, utilizing the conventional try/except
exception handler is more rational. By employing try/except
, you have the capability to capture the precise exception (like DoesNotExist
in Django ORM) and manage it as needed, whether it involves logging the error, tailoring the error message, or directing the user elsewhere.
List Retrieval
Let's take another example:
I want to write a program to retrieve all active blogposts with the given id & raise a 404 error if no items are found.
from django.shortcuts import get_list_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import BlogPost
from .serializers import BlogPostSerializer
class ActiveBlogPostListView(APIView):
def get(self, request):
queryset = get_list_or_404(BlogPost, is_active=True)
serializer = BlogPostSerializer(queryset, many=True)
return Response(serializer.data)
many=True
parameter is used in a DRF serializer to indicate that the serializer should handle multiple instances of the model, allowing it to serialize a queryset or list of objects.I hope with this few points of mine, I've been able to convince and not confuse you ๐ that you can do more with less code. GoodLuck as you write better codes henceforth โ.