Login

Tag "enumeration"

Snippet List

Django enumeration for model field choices

The problem with supplying a Django model field with choices parameter is the way you check a value of that field in an object. You do nasty things like this: if model_instance.choice_field == 1: The problem of getting rid of hard-coded numbers is recognized over the internet, but I haven't found any short and understandable solution. Basically, we need a enumeration in python, that is ok to use as the Django `choices` model field argument. I've seen a couple of solutions of DjangoSnippets. Mine is shorter and easier because it only works for integer field choices.

  • choices
  • integer
  • enumeration
Read More

More readable Enumeration class for Django choices

We currently use two-level tuples to specify choices of a field in models or forms. But, because it has only (value, verbose name) pair, the readability is bad whenever we indicate a specific choice value in our Python codes. So I made a small class that does "magic" for this: A Named Enumeration. Instead of `myobj.status == 0`, use `myobj.status == STATUS.UNREVIEWED`, for example.

  • choices
  • model
  • orm
  • enumeration
  • enum
Read More

2 snippets posted so far.