Skip to main content

Generating and Sorting on a Transient Property in a Django Model Class

I ran into an interesting little issue in a Django application today that led to what I thought was some pretty powerful stuff in Python and Django that I hadn't had to use before, so I thought I'd share.

I'm working on an application that to keep it generic I'll simply say deals with requests from users, and these requests require various levels of approval depending on the type and severity of the request.

Here's a basic Django model class that contains the fields relative to this example:


Basic stuff so far.

Where the wrinkle comes in is there is a page in the application that lists the requests ordered by date, but the date by which each request will be displayed and sorted depends upon the impact of the request as follows:
  • minor: use datetime_supervisor_approved
  • major: use datetime_admin_approved
  • severe: use datetime_president_approved
To state the issues succinctly:
  • The date on which I want to sort varies for each request
  • I don't want to store an additional, redundant field in the database simply to have a consistent name to use for sorting
  • Because the sort date isn't stored in the database I can't use order_by on a QuerySet
That last bullet was the killer. In Python it's simple enough to add attributes to a class on the fly, so I could loop over the QuerySet and use conditional logic around the change impact to add a new calendar_date field to each instance of the UserRequest class, but that's kind of ugly because the business logic winds up in a view function as opposed to being in the model, and still doesn't solve the inability to use order_by in the QuerySet.

Because I want to keep the business logic in the model (fat models FTW!), I looked into using a Python property to add a transient attribute to my UserRequest class that is the result of a function call.

Basically what this means in concrete terms is I'm adding a calendar_date attribute to my model class and the value of calendar_date is set by calling a function in the class itself that contains the aforementioned conditional logic around the request impact.

Here's the modified model class:


The big addition here is the _get_calendar_date function that returns a calendar date based on the impact of the request. This is added as an attribute to the class, but it's not saved to the database which is exactly what I wanted in this instance.

That solves one piece of the puzzle, but the other piece is sorting the requests based on this new transient property, which again can't be done by using order_by on the QuerySet since the field on which we want to order isn't in the database.

This is where Python's sorted() function comes in. sorted() can take any iterable (which the Django QuerySet is) and sort it based on a provided comparator function, and this is where I can leverage the transient calendar_date property to sort the requests.

Putting all the pieces together in the view function, here's how it looks:


Python's sorted() function is pretty powerful and straight-forward -- throw it an iterable and what to compare on, and it does the heavy lifting for you.

The only potentially tricky part of this is setting the key since it uses Python's lambda statement (great explanation here), which is Python's way of kinda sorta dipping a toe into the functional programming waters by letting you define an anonymous inline function.

In this case how the lambda plays out is to sort the QuerySet based on two attributes: first the transient calendar_date property that isn't stored in the database, and subsequently the request_impact attribute that is stored in the database. Perfect!

I'm sure none of this is rocket science to seasoned Python and Django veterans but since I hadn't run into the need to do this before I thought I'd document what I came up with both for my own future reference and hopefully for the benefit of others who made need to so something similar.

Comments

Daniel Wilson said…
Thanks for the help!

Popular posts from this blog

Installing and Configuring NextPVR as a Replacement for Windows Media Center

If you follow me on Google+ you'll know I had a recent rant about Windows Media Center, which after running fine for about a year suddenly decided as of January 29 it was done downloading the program guide and by extension was therefore done recording any TV shows.

I'll spare you more ranting and simply say that none of the suggestions I got (which I appreciate!) worked, and rather than spending more time figuring out why, I decided to try something different.

NextPVR is an awesome free (as in beer, not as in freedom unfortunately ...) PVR application for Windows that with a little bit of tweaking handily replaced Windows Media Center. It can even download guide data, which is apparently something WMC no longer feels like doing.

Background I wound up going down this road in a rather circuitous way. My initial goal for the weekend project was to get Raspbmc running on one of my Raspberry Pis. The latest version of XBMC has PVR functionality so I was anxious to try that out as a …

Setting Up Django On a Raspberry Pi

This past weekend I finally got a chance to set up one of my two Raspberry Pis to use as a Django server so I thought I'd share the steps I went through both to save someone else attempting to do this some time as well as get any feedback in case there are different/better ways to do any of this.

I'm running this from my house (URL forthcoming once I get the real Django app finalized and put on the Raspberry Pi) using dyndns.org. I don't cover that aspect of things in this post but I'm happy to write that up as well if people are interested.

General Comments and Assumptions

Using latest Raspbian “wheezy” distro as of 1/19/2013 (http://www.raspberrypi.org/downloads)We’lll be using Nginx (http://nginx.org) as the web server/proxy and Gunicorn (http://gunicorn.org) as the WSGI serverI used http://www.apreche.net/complete-single-server-django-stack-tutorial/ heavily as I was creating this, so many thanks to the author of that tutorial. If you’re looking for more details on …

The Definitive Guide to CouchDB Authentication and Security

With a bold title like that I suppose I should clarify a bit. I finally got frustrated enough with all the disparate and seemingly incomplete information on this topic to want to gather everything I know about this topic into a single place, both so I have it for my own reference but also in the hopes that it will help others.Since CouchDB is just an HTTP resource and can be secured at that level along the same lines as you'd secure any HTTP resource, I should also point out that I will not be covering things like putting a proxy in front of CouchDB, using SSL with CouchDB, or anything along those lines. This post is strictly limited to how authentication and security work within CouchDB itself.CouchDB security is powerful and granular but frankly it's also a bit quirky and counterintuitive. What I'm outlining here is my understanding of all of this after taking several runs at it, reading everything I could find on the Internet (yes, the whole Internet!), and a great deal…