49π
Maybe this question helps you: Set Django IntegerField by choices=β¦ name.
I quote from the accepted answer (with adjustments ;)):
Put this into your class (STATUS_CHOICES
will be the list that is handed to the choices
option of the field):
PENDING = 0
DONE = 1
STATUS_CHOICES = (
(PENDING, 'Pending'),
(DONE, 'Done'),
)
Then you can do order.status = Order.DONE
.
Note that you donβt have to implement an own method to retrieve the (readable) value, Django provides the method get_status_display
itself.
11π
what I usually do for this situation is:
models.py
from static import ORDER_STATUS
status = models.PositiveSmallIntegerField(choices=ORDER_STATUS)
static.py
ORDER_STATUS = ((0, 'Started'), (1, 'Done'), (2, 'Error'))
ORDER_STATUS_DICT = dict((v, k) for k, v in ORDER_STATUS)
Now you can do:
from static import ORDER_STATUS_DICT
order.status = ORDER_STATUS_DICT['Error']
- [Django]-Django Admin nested inline
- [Django]-Unique BooleanField value in Django?
- [Django]-What does this "-" in jinja2 template engine do?
8π
This is a very late answer, however for completeness I should mention that django-model-utils already contains a StatusField and even better a StatusModel. I am using it everywhere I need to have a status.
- [Django]-Django REST Framework: how to substitute null with empty string?
- [Django]-How to find pg_config path
- [Django]-What should I use instead of syncdb in Django 1.9?
- [Django]-How to find out the request.session sessionid and use it as a variable in Django?
- [Django]-Django template display item value or empty string
- [Django]-CSS styling in Django forms
2π
You donβt need your status_str
method β Django automatically provides a get_status_display()
which does exactly the same thing.
To reverse, you could use this:
def set_order_status(self, val):
status_dict = dict(ORDER_STATUS)
self.status = status_dict[val][0]
Now you can do:
order.set_order_status('Done')
- [Django]-What's the difference between CharField and TextField in Django?
- [Django]-How to 'bulk update' with Django?
- [Django]-How to squash recent Django migrations?
0π
Maybe stick a method on the model, like:
def status_code(self, text):
return [n for (n, t) in self.ORDER_STATUS if t == text][0]
Then youβd do:
order.status = order.status_code('Error')
- [Django]-Django 1.5 β How to use variables inside static tag
- [Django]-How to compare two JSON objects with the same elements in a different order equal?
- [Django]-How to format time in django-rest-framework's serializer?
0π
donβt do all those things.just make change in views.py as follows
context['value'] = Model_name.objects.order_by('-choice')
where
choice = ('pending','solved','closed')
- [Django]-ChoiceField doesn't display an empty label when using a tuple
- [Django]-How to break "for loop" after 1 iteration in Django template
- [Django]-Adding model-wide help text to a django model's admin form