Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get choice display on using .values

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.

like image 635
Garvit Jain Avatar asked Oct 19 '25 09:10

Garvit Jain


2 Answers

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
like image 131
Nafees Anwar Avatar answered Oct 21 '25 23:10

Nafees Anwar


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
like image 36
GCru Avatar answered Oct 22 '25 01:10

GCru