Entries published on November 2, 2007
Handle choices the right way
A lot of common use cases involve a model field which needs to accept values from a restricted set of choices; for example, a field for selecting a US state should, logically, only allow values which correspond to actual US states. In Django’s ORM, this is represented by using the “choices” argument when defining the field, and generally this provides a fairly easy solution.
But it’s not always perfect: while string-based values (such as those for a US state field, which are — in Django’s implementation — simply two-letter postal abbreviations like “VA” or “KS”) work pretty well with this system, numeric values are a bit trickier. As an example, consider the
Entry model I use for my blog (the full source code, if you’re interested, is in a Google Code repository), which has a “status” field to let me differentiate three different types of entries: …