choicefield - Request Clarification of Django Model Choice Code from Docs -


in official docs, https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices given example:

class student(models.model):     freshman = 'fr'     sophomore = 'so'     junior = 'jr'     senior = 'sr'     year_in_school_choices = (         (freshman, 'freshman'),         (sophomore, 'sophomore'),         (junior, 'junior'),         (senior, 'senior'),     )     year_in_school = models.charfield(max_length=2,                                       choices=year_in_school_choices,                                       default=freshman) 

what purpose of setting variables strings before, , in addition to, actual tuples of year_in_school_choices? strings used? these variables same ones used in tuple? if so, why? seems additional , unnecessary step.

it not in example before one, use different year_in_school_choices. clarifying.

update

since sitting here wrestling code speak, quick responses. add understanding. think @shang-wang has concise , responsive answer question far. 1+ reference get_foo_display(). in particular use case, choices admin tell end user how particular object has been evaluated. want 'human-readable' form of evaluations displays in final html template end user on site. in light of these answers, i'm wondering if best way achieve goal? solution :

`

html display table

name of object | evaluation

foo | foo.get_evaluation_display()

or maybe:

for foo in objects:
name of object | evaluation
foo.name | foo.get_evaluation_display()
'

the purpose of particular model display expert evaluations of foo end users. each foo can have many such evaluations. although quite verbose, these evaluations can categorized, hence choice field. users can click on read original evaluation in full if want. foo defined on different model, , linked evaluation model foreign key. get_foo_display() work here, since choice field isn't on model foo instance?

p.s, realize has become different question, if needs moved or whatever, i'm ok that, come directly original q&a. let me know. thx.

the variable year_in_school_choices served possible choices in field year_in_school. first value in each pair in year_in_school_choices 1 stored in database, while second value in each pair 1 show in form dropdown(if use default widget). individual selection declaration freshman = 'fr' make sure encapsulated in class. can following each student object:

# assign value student's year_in_school student.year_in_school = student.freshman student.save()  # print 'fr' db_value = student.year_in_school print db_value  # print 'freshman' pretty_display_value = student.get_year_in_school_display() print pretty_display_value 

django doc get_foo_display.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -