I'm constantly doing the following pattern in Django:
class MyModel(models.Model):
FOO = 1
BAR = 2
GOO = 3
BLAH_TYPES = (
(FOO, 'Foodally boogaly'),
(BAR, 'Bar bar bar bar'),
(GOO, 'Goo goo gaa gaa'),
)
TYPE_FOR_ID = dict(BLAH_TYPES)
ID_FOR_TYPE = dict(zip(TYPE_FOR_ID.values(), TYPE_FOR_ID.keys()))
blah = models.IntegerField(choices=BLAH_TYPES)
Is there a good pattern that other people follow that achieves the same effect (i.e. I have access to constants with names and dictionaries that go both ways) without so much code?
To create a constant in Django. Open your settings.py file and add a variable like MY_CONST = “MY_VALUE”.
According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.
The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using MaxLengthValidator . If you are writing an application that must be portable to multiple database backends, you should be aware that there are restrictions on max_length for some backends.
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.
Carl Meyer's django-model-utils library has an excellent solution for this - the Choices class, which allows you to declare a list of choices with access via human-readable attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With