Search code examples
djangodjango-modelsdjango-admindjango-modeladmin

For a Charfield with choices, how to use the human readable name in list_display through a foreignkey?


Let's assume I have the following :

models.py :

VALUE_CHOICES = (('0', 'ZERO'),
                 ('1', 'ONE'))

class ModelA(models.Model):
    def val(self):
        return self.model_b.value or ''

class ModelB(models.Model):
    modela = models.OneToOneField(ModelA, related_name="model_b", null=False)
    value = models.CharField(choices = VALUE_CHOICES)

and

admin.py :

class ModelAAdmin(ModelAdmin):
    list_display = ['val']

When I try to display my ModelA list in the admin site it displays 0 or 1 and not ZERO or ONE.

How could I modify this to make it display the human readable name from VALUE_CHOICES in the list from the admin site?


Solution

  • From the docs, and for the field val,

    class ModelAAdmin(ModelAdmin):
        list_display = ['get_val_display']
    

    This should do the job.

    [EDIT by OP] I didn't succeed to make it work like this but this kind of method was a really good suggestion. Here is how I used this get_FOO_display() method (and it worked like a charm).

    I only modified my ModelA.val() method :

    def val(self):
        return self.model_b.get_value_display()