覆盖Django模型中的get_FIELD_display方法 [英] Override get_FIELD_display method in Django model

查看:59
本文介绍了覆盖Django模型中的get_FIELD_display方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的模型中有一个名为 field 的字段,其中有一个 choices 参数定义了 get_field_display 方法要返回的值.

Let's say I have a field called field in my model, with a choices parameter defining the values to be returned by the get_field_display method.

我需要 get_field_display 方法来基于另一个字段返回不同的值.有什么方法可以覆盖 get_field_display ?

I need the get_field_display method to return a different value based on another field. Is there any way to override get_field_display?

这不起作用:

def get_field_display(self):
    if self.other_field == 1:
        return 'Other value'

    return super.get_field_display(self)

推荐答案

您不能调用 super ,因为该函数不是由父类定义的,而是由 ModelBase 定义的>元类.试试这个:

You can't call super because the function is defined not by the parent class but by the ModelBase metaclass. Try with this:

def get_field_display(self):

    if self.other_field == 1:
        value = 'Other value'
    else:
        field_object = self._meta.get_field('field')
        value = self._get_FIELD_display(field_object)

    return value

这篇关于覆盖Django模型中的get_FIELD_display方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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