简体   繁体   中英

How to access django choice field tuple in view?

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 ?

instance.get_years_of_experience_display()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM