Django: override get_FOO_display ()

In general, I am not familiar with overriding python methods and using the super () function.

question: 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 split my screen.

But super(A, self).get_unit_display() does not work.

+10
source share
2 answers

Usually you just override the method as you showed. But the trick here is that the get_FOO_display method get_FOO_display not in the superclass, so calling the super method will do nothing. The method is added dynamically by the field class when it is added to the model by the metaclass - see Source here (EDIT: deprecated link as a permalink ).

One thing you could do is define a custom subclass of Field for the field of your unit and override contribute_to_class so that it creates the method you need. This is a bit complicated, unfortunately.

(I do not understand your second question. What exactly are you asking?)

+8
source

You should be able to override any method in the superclass by creating a method with the same name in the subclass. The signature of the argument is not considered. For instance:

 class A(object): def method(self, arg1): print "Method A", arg1 class B(A): def method(self): print "Method B" A().method(True) # "Method A True" B().method() # "Method B" 

In the case of get_unit_display (), you do not need to call super () at all if you want to change the displayed value, but if you want to use super (), make sure you call it using the correct signature, for example:

 class A(models.Model): unit = models.IntegerField(choices=something) def get_unit_display(self, value): display = super(A, self).get_unit_display(value) if value > 1: display = display + "s" return display 

Note that we pass the value of super () get_unit_display ().

-3
source

All Articles