Django:override get_FOO_display() [英] Django: override get_FOO_display()
问题描述
问题是:可以覆盖 get_FOO_display()
?
$ a
单位= models.IntegerField(choices = something)
def get_unit_display(self,value):
...使用super(A,self).get_unit_display()
我想覆盖get_FOO_display(),因为我想使我的显示复数。
但 super(A,self).get_unit_display()
不行
通常你会覆盖一个你所显示的方法。但是这里的诀窍是,超级类不存在 get_FOO_display
方法,所以调用超级
方法将不会执行任何操作在所有该方法在通过元类添加到模型时由字段类动态添加 - 请参阅这里的源。
您可以做的一件事是为您的 unit
字段,并覆盖 contribut_to_class
,以便构建所需的方法。不幸的是有点棘手。
(我不明白你的第二个问题,你究竟在问什么?)
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.
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.
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?)
这篇关于Django:override get_FOO_display()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!