在ModelChoiceField Django中使用__unicode__以外的方法 [英] Use method other than __unicode__ in ModelChoiceField Django

查看:165
本文介绍了在ModelChoiceField Django中使用__unicode__以外的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django的某些表单上工作。一个字段是模型中的 ForeignKey ,因此在表单中表示为 ModelChoiceField ModelChoiceField 目前使用模型的 __ unicode __ 方法来填充列表,这不是我想要的行为。我想要使​​用模型的另一种方法。从文档中,看起来我可以强制我自己的 QuerySet ,但是我看不出如何帮助我使用除 __ unicode__之外的方法



如果可以的话,我真的宁愿避免与默认表单方法离婚。



任何建议?

解决方案

不是一个自定义查询器,而是将您的查询器转换为列表。如果你只是做 choices = some_queryset Django做出以下形式的选择:

 (item.pk,item .__ unicode __())

所以只要自己做一个列表理解:

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


I'm working on some forms in Django. One field is a ForeignKey in the model, so represented as a ModelChoiceField in the form. The ModelChoiceField currently uses the __unicode__ method of the model to populate the list, which isn't my desired behavior. I'd like to be able to use another method of the model. From the docs, it looks like I can force my own QuerySet, but I can't see how this would help me use a method other than __unicode__.

I'd really rather avoid divorcing this from the default form methods if at all possible.

Any suggestions?

解决方案

Not so much a custom queryset, but converting your queryset to a list. If you just do choices=some_queryset Django makes the choices in the form of:

(item.pk, item.__unicode__())

So just do it yourself with a list comprehension:

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

这篇关于在ModelChoiceField Django中使用__unicode__以外的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆