Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display field choice as part of model string name

Tags:

From the django documentation, what if I had

GENDER_CHOICES = (     ('M', 'Male'),     ('F', 'Female'), )  class Person(models.Model):     name = models.CharField(max_length=20)     gender = models.CharField(max_length=1, choices=GENDER_CHOICES)      def __str__(self):             return "%s [%s]" % (self.name, self.gender) 

What if I wanted the __str definition to display as the full name (Male or Female) for self.gender instead of M or F?

like image 235
Ed. Avatar asked Jan 22 '12 15:01

Ed.


People also ask

How do you define choice fields in Django?

Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.

How do you add fields to a model?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

What are model fields?

Field models are used to calculate the values of field functions under given boundary and loading conditions. Field functions are physical quantities which depend on their geometrical location, such as temperature (a scalar field) or velocity (a vector field).


1 Answers

Use get_gender_display():

return u"%s [%s]" % (self.name, self.get_gender_display()) 

Note, if you're not using Python 3+ you should be defining __unicode__ rather than __str__.

like image 163
Daniel Roseman Avatar answered Nov 07 '22 06:11

Daniel Roseman