6

我正在处理 Django 中的一些表单。一个字段是ForeignKey模型中的 a,因此在表单中表示为 a ModelChoiceField。当前ModelChoiceField使用__unicode__模型的方法来填充列表,这不是我想要的行为。我希望能够使用模型的另一种方法。从文档看来,我可以强制使用自己的QuerySet,但我看不出这将如何帮助我使用__unicode__.

如果可能的话,我真的宁愿避免将其与默认表单方法分离。

有什么建议么?

4

2 回答 2

10

您可以覆盖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)
于 2012-07-11T16:36:37.017 回答
1

与其说是自定义查询集,不如说是将您的查询集转换为列表。如果你只是这样做,choices=some_querysetDjango 会以以下形式做出选择:

(item.pk, item.__unicode__())

因此,只需使用列表理解自己做:

choices=[(item.pk, item.some_other_method()) for item in some_queryset]
于 2012-07-11T16:34:25.240 回答