您可以覆蓋label_from_instance
指定不同的方法:
from django.forms.models import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.my_custom_method()
然後,您可以改爲在您的表單中使用此字段。此方法旨在在子類中重寫。這裏是原始來源django.forms.models
:
# this method will be used to create object labels by the QuerySetIterator.
# Override it to customize the label.
def label_from_instance(self, obj):
"""
This method is used to convert objects into strings; it's used to
generate the labels for the choices presented by this object. Subclasses
can override this method to customize the display of the choices.
"""
return smart_unicode(obj)
謝謝。真的很方便。 – TimD 2012-07-11 17:15:17