2012-07-11 18 views
6

我正在研究Django中的某些窗體。一個字段是模型中的ForeignKey,因此在表單中表示爲ModelChoiceFieldModelChoiceField當前使用模型的__unicode__方法來填充列表,這不是我想要的行爲。我希望能夠使用模型的另一種方法。從文檔看起來,我可以強制自己的QuerySet,但我看不到這將如何幫助我使用__unicode__以外的方法。ModelChoiceField中__unicode__以外的其他使用方法Django

如果可能的話,我寧願避免將它從默認窗體方法中分離出來。

有什麼建議嗎?

回答

1

不是一個自定義的查詢集,而是將您的查詢集轉換爲一個列表。如果你只是做choices=some_queryset Django中所做出的選擇的形式:

(item.pk, item.__unicode__()) 

因此,只要自己做一個列表理解:

choices=[(item.pk, item.some_other_method()) for item in some_queryset] 
+0

謝謝。真的很方便。 – TimD 2012-07-11 17:15:17

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) 
相關問題