Reputation: 10265
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.
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
?
This doesn't work:
def get_field_display(self):
if self.other_field == 1:
return 'Other value'
return super.get_field_display(self)
Upvotes: 1
Views: 2240
Reputation: 1129
What you can do is to create a different function in the same model, then monkey patch it. For example, in admin.py you may do something like:
ClassName.get_field_display = ClassName.get_patched_field_display
It's not very 'nice' but it works for me.
Upvotes: 1
Reputation: 7235
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
Upvotes: 4