You hear a lot about “mixins”, but what exactly is a mixin? And, how can you create your own?
A Mixin is a special kind of inheritance in Python (and other object-oriented languages) and it’s starting to get a big rise in Django / Web Application Development. You can use a Mixin to allow classes in Python to share methods between any class that inherits from that Mixin. So what does it look like?
from django.http import JsonResponse class JSONResponseMixin(object): """ A mixin that can be used to render a JSON response. """ def render_to_json_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ return JsonResponse( self.get_data(context), **response_kwargs ) def get_data(self, context): """ Returns an object that will be serialized as JSON by json.dumps(). """ # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. return context
This is an example from the Mixin Documentation on djangoproject.com. As you can see just looking at this example, it’s just a plain Python class.
Now, you can pass it in to a class and call the methods just as you would if the method was on the class as
from django.views.generic import TemplateView class JSONView(JSONResponseMixin, TemplateView): def render_to_response(self, context, **response_kwargs): return self.render_to_json_response(context, **response_kwargs)
This is useful if you have some code that you want to reuse among different classes in your code.
Can you think of a function that you would need to reuse in your code? Try this out! Create a Mixin and pass it into all the places that need some reusable code snippets!
Need help with Django REST Framework? Django REST Framework documentation a little confusing?
Join me for my FREE Django REST Framework email course:
Django REST Framework Email Course
You'll get 1 lesson everyday for 7 days.
- Request Methods
- Basic Authentication
- JQuery Integration
- AngularJS Integration
Similar PostsWhat is SECRET_KEY in Django?
How to Use a Virtual Environment to run you Django app