views:

21

answers:

3

Hi all,

I would like to display priority information in a drop down. Currently i am using a integer field to store the priority, but i would like to display high/medium/low instead of letting user type in a priority.

A way to approximate this is to use a Priority database which stores 3 elements, 1:high, 2:medium, 3:low, but it seems like an overkill.

Any easier way would be much appreciated!

Jason

+1  A: 

You should be able to add choices to the model element

So:

class myModel(models.Model):
    mydata = models.CharField(max_length=4, choices= ((u'H', u'High',), (u'M', u'Medium'), (u'L', u'Low')))

Would store H,M,L in the DB, but present High, Medium, Low. Admin defaults fields with the choices attribute to a drop down selector

mcpeterson
I'd say assigning the priorites to integers rather than to characters makes probably more sense, as you can then order your objects more easily by priority in a queryset (if that's needed somewhere).
lazerscience
Sure, there are many ways to modify and improve if you want.
mcpeterson
+2  A: 

You can specify choices for a field http://www.djangoproject.com/documentation/models/choices/.

PRIORITY_CHOICES = ((1, 'High'),
                    (2, 'Medium'),
                    (3, 'Low'))

class MyModel(models.Model):
    priority = models.IntegerField(choices=PRIORITY_CHOICES)
lazerscience
+2  A: 

You could write your model like this:

from django.db import models

class Priority(models.Model):
    PRIORITY_LOW = 3
    PRIORITY_MEDIUM = 2
    PRIORITY_HIGH = 1

    PRIORITY_CHOICES = (
        (PRIORITY_LOW, 'low'),
        (PRIORITY_MEDIUM, 'medium'),
        (PRIORITY_HIGH, 'high'),
    )

    priority = models.IntegerField(choices=PRIORITY_CHOICES)

You read more from the documentation

the_void
You have mixed up the order of value / Text for the choices, it should be eg. (PRIORITY_LOW, 'low')
lazerscience
Thank you very much for your solution! Though the order is wrong for what i need, eg. 'low' and PRIORITY_LOW need to be exchanged to print out low in the drop down menu
FurtiveFelon
Yes, you're right, I've mixed up the values. I've updated them with the correct values.
the_void