Tim*_*imD 6 python forms django django-forms django-queryset
我正在Django的一些表格上工作.一个字段是ForeignKey模型中的一个字段,因此ModelChoiceField在表单中表示为a .在ModelChoiceField目前使用的__unicode__模型的方法来填充列表,这不是我希望的行为.我希望能够使用该模型的另一种方法.从文档中,看起来我可以强迫自己QuerySet,但我看不出这将如何帮助我使用除了以外的方法__unicode__.
如果可能的话,我真的宁愿避免将其与默认表单方法分开.
有什么建议?
Sim*_*ser 10
您可以覆盖label_from_instance以指定其他方法:
from django.forms.models import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.my_custom_method()
Run Code Online (Sandbox Code Playgroud)
然后,您可以在表单中使用此字段.此方法旨在在子类中重写.以下是原始资料来源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)
Run Code Online (Sandbox Code Playgroud)
与其说是自定义查询集,不如说是将查询集转换为列表。如果你只是这样做,choices=some_querysetDjango 会以以下形式做出选择:
(item.pk, item.__unicode__())
Run Code Online (Sandbox Code Playgroud)
因此,只需使用列表理解自行完成即可:
choices=[(item.pk, item.some_other_method()) for item in some_queryset]
Run Code Online (Sandbox Code Playgroud)