Reputation: 19472
Is there a way to overload Django's get_FIELD_display()
function properly? When I call the function from inside itself, the result is a recursion. But I can't call it using super()
either, as it's not a parent class' method but a method created by the metaclass...
The goal is to have a common interface for getting a displayable version of a CHOICE
field (which is given by get_FIELD_display
), but with the possibility to customize it in some specific cases.
Example:
# This does not work because it results in recursion
def get_opposition_state_display(self):
"""Overloading of default function."""
value = self.get_opposition_state_display()
if self.opposition_state == 4:
return '%s %s' % (value, self.opposition_date.strftime('%d.%m.%Y'))
return value
Upvotes: 3
Views: 1016
Reputation: 81
To override get_FOO_display you need something like this:
field_name = models.PositiveSmallIntegerField('Field', choices=some_choices)
def _get_FIELD_display(self, field):
f_name = field.name
if f_name == 'field_name':
return 'what_you_need'
return super(YourModelName, self)._get_FIELD_display(field=field)
Upvotes: 2
Reputation: 28637
updated
field = self._meta.get_field('opposition_state')
value = self._get_FIELD_display(field)
Upvotes: 5