[ACCEPTED]-How does get_FIELD_display (in django) work?-django
This is all managed via the metaclass - you'll 21 see in the source that the Model class defines 20 a
__metaclass__ attribute, which is set to
ModelBase. The metaclass 19 is to the class as a class is to an instance.
So 18 the metaclass is called when a Django class 17 is defined. The metaclass then executes various 16 code which determines the properties of 15 the model class. So, it iterates through 14 the fields that are declared on the model 13 class, and assigns each one as an instance 12 attribute - this is how Django's declarative 11 syntax works. It then calls each field's 10
contribute_to_class method, which adds any field-specific methods 9 to the class itself - and one of those methods 8 is the
_get_FOO_display method. You can see the source for 7 this in
In order to change
get_myfieldname_display, it uses 6 a technique called "currying", which means 5 that it defines a new function that applies 4 the original method with a defined parameter 3 - in this case, the name of the field.
If 2 you're interested in all this, Marty Alchin's 1 book Pro Django has an excellent explanation.
The magic __getattr__ method on classes can be used 4 to implement this kind of functionality.
__getattr__ is 3 called for every
attribute does not exist 2 on
obj, and the implementation can return whatever 1 it wishes.
More Related questions