Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: override get_FOO_display()

Tags:

python

django

In general, I'm not familiar with python's way of overriding methods and using super().

question is: can I override get_FOO_display()?

class A(models.Model):
   unit = models.IntegerField(choices=something)

   def get_unit_display(self, value):
     ... use super(A, self).get_unit_display() 

I want to override get_FOO_display() because I want to pluralize my display.

But super(A, self).get_unit_display() doesn't work.

like image 577
dtc Avatar asked Dec 18 '12 01:12

dtc


2 Answers

Now in Django > 2.2.7:

Restored the ability to override get_FOO_display() (#30931).

You can override:


    class FooBar(models.Model):
        foo_bar = models.CharField(_("foo"),  choices=[(1, 'foo'), (2, 'bar')])
    
    
   
        def get_foo_bar_display(self):
            return "something"

like image 91
Omid Raha Avatar answered Sep 21 '22 15:09

Omid Raha


Normally you would just override a method as you have shown. But the trick here is that the get_FOO_display method is not present on the superclass, so calling the super method will do nothing at all. The method is added dynamically by the field class when it is added to the model by the metaclass - see the source here (EDIT: outdated link as permalink).

One thing you could do is define a custom Field subclass for your unit field, and override contribute_to_class so that it constructs the method you want. It's a bit tricky unfortunately.

(I don't understand your second question. What exactly are you asking?)

like image 39
Daniel Roseman Avatar answered Sep 23 '22 15:09

Daniel Roseman