[Django]-How does get_FIELD_display (in django) work?

32đź‘Ť

âś…

This is all managed via the metaclass – you’ll see in the source that the Model class defines a __metaclass__ attribute, which is set to ModelBase. The metaclass is to the class as a class is to an instance.

So the metaclass is called when a Django class is defined. The metaclass then executes various code which determines the properties of the model class. So, it iterates through the fields that are declared on the model class, and assigns each one as an instance attribute – this is how Django’s declarative syntax works. It then calls each field’s contribute_to_class method, which adds any field-specific methods to the class itself – and one of those methods is the _get_FOO_display method. You can see the source for this in django/db/models/fields/__init__.py.

In order to change _get_FIELD_display to get_myfieldname_display, it uses a technique called “currying”, which means that it defines a new function that applies the original method with a defined parameter – in this case, the name of the field.

If you’re interested in all this, Marty Alchin’s book Pro Django has an excellent explanation.

2đź‘Ť

The magic __getattr__ method on classes can be used to implement this kind of functionality. __getattr__ is called for every obj.attribute where attribute does not exist on obj, and the implementation can return whatever it wishes.

Leave a comment