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!
Struggle with the Django Documentation?
If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!