Reputation: 11
I have a model as below:
class EmployeeJobPost(models.Model):
title = models.CharField(max_length=100,blank=True)
years_of_experience = models.IntegerField(default=0, blank=True, null=True, choices=YEARS_OF_EXPERIENCE_CHOICES)
YEARS_OF_EXPERIENCE_CHOICES = (
(0, '0-1 Years'),
(1, '1+ Years'),
(5, '5+ Years'),
(10, '10+ Years'),
)
How can I access YEARS_OF_EXPERIENCE_CHOICES in a django view ?
Upvotes: 0
Views: 2809
Reputation: 8285
In case you were looking to get the tuple of choices instead of just the currently selected display value, you can access the model's field through the instance's _meta attribute.
instance = EmployeeJobPost.objects.get(id=<some_id>)
choices = dict(instance._meta.get_field_by_name('years_of_experience')[0].flatchoices)
Now you can access all of the other options, aside from the currently selected one. choices.get(0)
, choices.get(2)
, etc. Otherwise, you can create a form field object and access the choices from there. The other thing you can do is import the constant from your models.py module.
from my_app.models import YEARS_OF_EXPERIENCE_CHOICES
choices = dict(YEARS_OF_EXPERIENCE_CHOICES)
Upvotes: 3