It should be reasonably well-known by now that querysets are lazy. That is, simply instantiating a queryset via a manager doesn't actually hit the database: that doesn't happen until the queryset is sliced or iterated. That's why the first field definition in the form below is safe ...
more ...There's a question I see quite a lot at StackOverflow and the Django Users group regarding aggregation in Django. It goes like this: I know how to annotate a max/min value for a related item on each item in a queryset. But how do I get the actual ...
more ...Here are the slides from my talk at Europython 2010, Advanced Django ORM Techniques.
The talk is mainly a summary of the query optimisation tricks I've previously talked about on this blog, although I did begin by explaining briefly how models, fields ...
more ...I previously wrote about a thread-safety bug I encountered in writing a middleware object. I recently found a very similar situation in a class-based view I was modifying, and thought it was worth writing up what the problem was and how I solved it. Interestingly, there's a discussion going ...
more ...I love Django's aggregation framework. It very successfully abstracts the common aggregration tasks into a Pythonic syntax that sits extremely well with the rest of the ORM, and the documentation explains it all without a single reference to SQL.
But sometimes that very abstraction gets in the way of ...
more ...One of the features I quite missed when I first moved from Komodo to Textmate as my main editor was autocompletion. Although I didn't use it very much, it was occasionally useful to be reminded of the methods available on a class, without having to look up the documentation ...
more ...So, I've learned my lesson. When I first set up this blog I said at great length that I'd prefer using Django's built-in commenting system than the third-party Disqus service that Mingus uses by default.
Well, after a week of trying to stop a flood of spam ...
more ...Occasionally I need to create a temporary model within a Django application.
The most recent occasion for this was a one-off management command I was writing to import some data from a legacy system. The old database, for some reason, eschewed foreign keys in favour of char fields in a ...
more ...One common database operation that isn't supported out of the box by Django's ORM is create_or_update
- in other words, given a set of parameters, either update an existing object or create a new one if there isn't one already.
The naive implementation is to do a get ...