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?
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.
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.
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.
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).
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With