1

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)
ySgPjx
  • 10,165
  • 7
  • 61
  • 78

2 Answers2

4

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
Chewie
  • 7,095
  • 5
  • 29
  • 36
  • Doesn't work for me. I even tried with an override that only prints a string and the code is not even executed. I'm using Django 1.3.0. – ySgPjx Oct 30 '12 at 13:13
  • How are you checking this? Did you open a Django shell, retrieved an instance of your model, and call its `get_field_display()` to see what's being returned? – Chewie Oct 30 '12 at 14:05
  • Yes, that's exactly what I did. I also added a print statement at the beginning of the method but don't see anything printed in Django's log. – ySgPjx Oct 30 '12 at 14:51
  • @Chewie this worked for me. This should be marked as the answer. – coler-j Sep 28 '17 at 13:52
1

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.

user2111922
  • 891
  • 9
  • 9