Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically add constants for each of the choices in a Django model

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?

like image 453
guidoism Avatar asked Feb 23 '11 00:02

guidoism


People also ask

How do you set constants in Django?

To create a constant in Django. Open your settings.py file and add a variable like MY_CONST = “MY_VALUE”.

What is AutoField in Django?

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.

What is Max_length in Django?

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.

How do you define choice fields in Django?

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.


1 Answers

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.

like image 126
Daniel Roseman Avatar answered Oct 12 '22 03:10

Daniel Roseman