For a Model
with field type
, is there any way to get the choice display value on using Model.objects.values()
? I tried Model.objects.values('get_type_display')
but it doesn't work.
You can't do that. values
is a built in django queryset method which is used to get dictionaries of data instead of model instances you can read more about it here.
The conventional (and proper) way of attaching choices with model for a field is using static variable like this.
class MyModel(models.Model):
TYPE_CHOICES = (
# (<DB VALUE>, <DISPLAY_VALUE>)
('a', 'Choice A'),
('b', 'Choice B'),
)
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
You can access choices for type field outside model like this.
MyModel.TYPE_CHOICES
Where I do call .values
of choice fields into my queryset I deal with this in the following way:
Assume the following model
from enum import Enum
class TypeChoice(Enum):
a = 'class A'
b = 'class B'
class MyModel(models.Model):
type = models.CharField(max_length=1, choices=[(tag.name,tag.value) for tag in TypeChoice])
Using the query my_qset = MyModel.objects.values('type')
the display values are available as:
for item in my_qset:
print(TypeChoice[item].value)
To deal with this in my templates I write a custom template filter, say type_display
:
from django import template
import TypeChoice
register = template.Library()
@register.filter
def type_display(var):
return TypeChoice[var].value
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