Extra objects from your URLs with cleaner views and less repetition — Django

For those moments when a single object is not enough

Ícaro
Lemon Code
Published in
2 min readDec 29, 2018

--

Photo by Irina on Unsplash, snippet by @carbonapp
Photo by Irina on Unsplash, snippet from @carbonapp

When working with Django class-based views it’s often common to simply use the view’s object to populate forms, perform validations and other actions depending on your business logic.

What if you need to do that in an instance that is not the current view’s object? You could get it from a relation or load it manually which is trivial, but things can get messier depending on what your view needs to do like below:

Doing this can lead to not so great code because it’s not DRY, it’s hard to refactor, can be confusing and have other problems that you’ll only find out six months later when you need to come back to maintain and change it.

You and your team trying to decipher complicated code

Django is amazingly built so we can take inspiration from what it already provides us to create or own classes, functions and more. With that in mind, the SingleObjectMixin does exactly what we needed above as it’s used to “Provide the ability to retrieve a single object for further manipulation.”

So we can create a new mixin with a behavior simpler but similar to it which can be used along without conflict in how they are executed:

Define an extra model and it’s instance will be loaded based on the view’s URL arguments (the PK or a slug can be used). It’s simple, gets one job done and is reusable and certainly helps with the problems we faced before.

Below we have a sample of it’s usage that includes setting up the mixin and using it in the view and in it’s URL.

Instead of using relations and functions to load the instance, we simply setup the mixin with what we needed and used it’s object_extra accessors for that.

If you are feeling adventurous, you could even expand the mixin to load two or more extra objects by adding more model fields and URL arguments.

All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.

🍋 🍋 🍋

--

--