I've come to believe Django's way of defining database tables is wrong
Django defines both database tables and HTML forms in the same way, a way that seems to be extremely common in web frameworks across several languages (and which I think first surfaced in Rails, although I may well be wrong there):
class AForm(...): login = forms.CharField(...) email = forms.EmailField(...) ...
This is very appealing initially and Django goes well out of its
way to make it all work. But over time I've
come around to feeling that this is in fact the wrong way to do
forms, database tables, and so on in Python. Why not boils down to
one famous sentence from '
import this' (aka the zen of Python):
Explicit is better than implicit.
Django form classes and database classes are full to the brim of implicit magic. They're essentially an illusion. Worse, they're not really a very Pythonic illusion. We accept the illusion because it's convenient and this way of defining forms and tables has become more or less standard, but that doesn't mean that it's right in Python.
(My view is that the initial Rails version was a reasonably natural looking DSL that happened to also be valid Ruby code with the right mangling. The Python version is clearly not something you can read as a DSL, so I think that the seems show much more; it looks like Python but it's kind of bizarre Python.)
Given the Tim Peters remark I led with, I think a more Pythonic way
would make explicit various things that are currently implicit. I
don't have a good handle on what that would look like, though.
Doing the setup in class
__init__? Defining the table or form
layout by calling code instead of defining a class? Either would
be (or at least could be) more explicit and less magical.
(Part of the issue is that Python has decided that structures with named fields are only really available as classes. Once you have classes, all sorts of temptations start materializing and looking at least partly natural.)
PS: It's my view that the magical, illusory nature of Django form and table definitions starts showing through very distinctly once you want to do more complex things with them. Like much magic, it works best if you don't touch it at all.
Comments on this page:Written on 30 January 2015.