【问题标题】:Use method other than __unicode__ in ModelChoiceField Django在 ModelChoiceField Django 中使用 __unicode__ 以外的方法
【发布时间】:2012-07-11 07:56:54
【问题描述】:
我正在 Django 中处理一些表单。一个字段是模型中的ForeignKey,因此在表单中表示为ModelChoiceField。 ModelChoiceField 当前使用模型的 __unicode__ 方法来填充列表,这不是我想要的行为。我希望能够使用模型的另一种方法。从文档看来,我可以强制使用自己的 QuerySet,但我看不出这将如何帮助我使用 __unicode__ 以外的方法。
如果可能的话,我真的宁愿避免将其与默认表单方法分离。
有什么建议吗?
【问题讨论】:
标签:
python
django
forms
django-forms
django-queryset
【解决方案1】:
您可以覆盖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)
【解决方案2】:
与其说是自定义查询集,不如说是将您的查询集转换为列表。如果你只是做choices=some_queryset Django 会以如下形式做出选择:
(item.pk, item.__unicode__())
所以你自己做一个列表理解:
choices=[(item.pk, item.some_other_method()) for item in some_queryset]