Django: override get_FOO_display()

前端 未结 4 1808
無奈伤痛
無奈伤痛 2021-01-02 03:16

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

question is: can I override get_FOO_display()?



        
4条回答
  •  一整个雨季
    2021-01-02 03:51

    You should be able to override any method on a super class by creating a method with the same name on the subclass. The argument signature is not considered. For example:

    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 have to call super() at all, if you want to change the display value, but if you want to use super(), ensure that you're calling it with 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 are passing value to the super()'s get_unit_display().

提交回复
热议问题