Django:override get_FOO_display() [英] Django: override get_FOO_display()

查看:747
本文介绍了Django:override get_FOO_display()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我不熟悉python的覆盖方法和使用super()的方法。



问题是:可以覆盖 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆