top of page
Writer's pictureNIKOLAS SCHAEFER

Class vs Function based views in Django


What is Django?

Django is a python-based backend web framework built around developing quickly. Django is used in production by Instagram, Pinterest, Nasa, YouTube, Dropbox, and more. Django has a robust supportive community and is a batteries included framework.


Why we love Django

Django utilizes an ORM to interact with a database which makes it easy for developers to use a database without learning SQL. Django is in python, a loved language that is easy to use and develop with. Django has built in authentication and authorization with their middleware and will automatically store sessions. Django is a scalable framework that allows for easy development with rest API CRUD operations. It has a built in admin panel for management and easy development.


I also wrote a blog on this topic



What are Views?

Views in Django are how Django will handle a request from a URL whether that be get or post. It will return renders of templates and JSON data.


Function Based


A typical function based view will look similar to this

@api_view(["post", "get"]) # Function Decorator
def function_based_view(request):
    """
    the function body
    """
    return HttpResponse({}) #  typically filled with data

The request is passed in as a function parameter in which you then can import models or find. In function based views you will typically have to do more of the heavy lifting in the code along with more customization.


Class Based


class based views often look like this

class class_based_view(APIView): # will vary the inherited class
    def get(request):
        return HttpResponse({})
    def post(request):
        return HttpResponse({})

Class based views will often change their inheritance class based on how they work. It allows for more functionality but will be more difficult to learn and master. Class based views get easier and faster functionality.


Conclusion

you can do anything with class based views as you can with function based views. Function based views require more code and often longer development. Class based views often will be able to accomplish the same tasks easier and with less code along with providing a faster view.

13 views2 comments

Recent Posts

See All

2 Comments


SHANELLE PETERSON
SHANELLE PETERSON
Feb 18, 2021

This is absolutely fascinating! I loved how you went into depth.

Like

SOPHIA SCOTT
SOPHIA SCOTT
Feb 17, 2021

Wow, this insight is just incredible. I have been amazed and it’s a beautiful blog. I have truly been enlightened

Like
bottom of page