djangodjango-modelsmultiple-choice

Django - Choices for Models


I have been searching and looking through docs, but I want to ask and confirm for the best solution here.

Trying to define model choices.

  1. 'yes, no and not sure' choice From Radio Select
  2. How would I define for Multiple Choices

Simple Example: In my models.py, I have

class Property(models.Model):
    name = models.CharField()

class Feature(models.Model):
    YES_CHOICES = (       # example of 1, there can be only one selection
        ('YES', 'Yes'),
        ('NO', 'No'),
        ('NOT_SURE', 'Not Sure')
    )
    PARKING_CHOICES = (    # example of 2, there can be multiple selections
        ('GARAGE', 'Garage'),
        ('STREET', 'Street'),
        ('PRIVATE_LOT', 'Private Lot'),
        ('VALET', 'Valet'),
    )

    nearby_school = models.CharField(max_length=8, choices=YES_CHOICES)
    parking_options = models. MultipleChoiceField(choices=PARKING_CHOICES)

class PropertyFeature(models.Model)
    property = models.ForeignKey(Property)
    feature = models.ForeignKey(Feature)
    ...

Are those best ways to do it?

  1. Should I use NullBooleanField instead for yes, no , not sure question?
  2. Is that a correct way for defining and storing for multiple choice answers? Sometimes, I see people using manytomany objects.

Just want to use the most efficient and the easiest method offered from Django.


Solution

  • Yes, NullBoolean is appropriate, but if there are more options that don't fit the profile of NullBoolean, I'm in favor of IntegerField for readability and consistency across options.

    Null could intuitively mean n/a, but as you add more single choice questions, I think it's even more intuitive to use an IntegerField mapped to static variables.

    Also for this type of scenario where the user will probably filter properties based on these features, it's useful not to have to special case Null in your dynamic query.

    Example:

    ...filter(Q(nearby_school__isnull=True) | Q(nearby_school='NO')),
        other_choice='SOME_CHOICE')
    # vs
    ...filter(Q(nearby_school=Feature.NOT_SURE) | Q(nearby_school=Feature.NO)), 
        other_choice=Feature.SOME_CHOICE)
    

    This ancient post still serves as a great reference: http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/

    class Feature(models.Model):
        YES = 0
        NO = 1
        NOT_SURE = 2
        SOMETIMES = 3
        YES_CHOICES = ( 
            (YES, 'Yes'),
            (NO, 'No'),
            (NOT_SURE, 'Not Sure'),
            (SOMETIMES, 'Sometimes'), # extensible.
        )
    

    As for a multiple choice field, I do think using a m2m field is the easiest/best way.

    You could set up your forms.MultipleChoiceField to store data as a comma separated field & display appropriately, but the fact that you can query the m2m field easily is a huge benefit + it works right out of the box with ModelMultipleChoiceField.