Django ’sans magie’
I’ve been busy these last two days converting my Django-based project over to the newest development trunk of Django, which now includes he results of all the work done on the “Magic Removal Branch” after that has been merged over.
The aim of the Magic Removal branch was to clean up the Django framework syntax and get rid of a lot of the so-called “magic” (hence the name): Auto-generated package names, auto-generated accessors for fields, etc.
There was one hiccup — the new development version no longer supports model inheritance (the Desk model inherits from the Furniture model which inherits from the StuffYouCanBurn model). As a result, after some whining in the newsgroup, I had to flatten the inheritance hierarchy, inlining the inherited properties into the classes and make them all inherit from the common Django base class for data models. It’s not nice, every copy/paste operation hurt, but if the result means that I can benefit from all the other changes in Django (and not launch my application with a codebase which will soon be obsolete and a lot of data migration at some point in the future), it had to be done.
Apart from this issue, the new Django version is a joy to work with. Everything is extremely logical and you find yourself wondering why it’s ever been any different. Take the ORM mapping of many-to-many-fields (a Course has several Students, and a Student has multiple Courses): Previously, you had an autogenerated (magic) setter and getter, one of which returned a list of ‘real’ objects, the other insisted on taking a list of object ids. So there was some converting to and fro in order to add an element. The new code for this gives you a collection object (more or less), to which you can simply add() the new object (not its ID!), save the model et voilá! (to remain linguistically consistent with the headline) - done.
Also, the way queries from the object base are created and chained (a little bit of selecting, some ordering and then just the first few elements) is a lot more readable. Where previously you had to write
students.get_list(name__exact='Einstein', order_by=('-birthday', 'relativity'), offset=2, limit=3)
(where ’students’ is one of these auto-generated aliases for all instances of the class ‘Student’) it’s now:
Student.objects.filter(name='Einstein').order_by('-birthday', 'relativity')[2:3]
which I find a lot easier to read and understand.
All in all, this is a great step forward for Django and again deserves a round of applause for all developers (and documentation-writers) involved.
Bookmark on del.icio.us
Add this post to digg.com
Bookmark on reddit.com
July 9th, 2006 at 1:49 pm
I just started with Django, with the “sand magic” branch, currently trunk from the Subversion. I also miss inheritance, but I’ll have to live without it, there’s so much other benefits of Django. Looks like I’ll refactor my database with it and build a browsing tool quickly.