python - Django 形式的懒惰选择

标签 python django forms lazy-evaluation

我有一个这样的 Django my_forms.py:

class CarSearchForm(forms.Form):  
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=bodystyle_choices())  

每个选择都是例如(“轿车”、“轿车(15 辆)”)。所以选择是由这个函数计算出来的。

def bodystyle_choices():  
    return [(bodystyle.bodystyle_name, '%s (%s cars)' %  
          (bodystyle.bodystyle_name, bodystyle.car_set.count()))  
          for bodystyle in Bodystyle.objects.all()]

我的问题是每次我只导入 my_forms.py 时都会执行选择函数。我认为这是由于 Django 声明其字段的方式:在类中但不在类方法中。这很好,但我的 views.py 导入了 my_forms.py,因此无论使用哪个 View ,都会在每个请求上完成选择查找。

我认为也许不带括号的选择=bodystyle_choices 会起作用,但我得到:

'function' object is not iterable

显然我可以使用缓存并将“import my_forms”放在所需的 View 函数中,但这并没有改变重点:我的选择需要是懒惰的!

最佳答案

你可以使用“懒惰”功能:)

from django.utils.functional import lazy

class CarSearchForm(forms.Form):  
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())

非常好的实用功能!

关于python - Django 形式的懒惰选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569696/

相关文章:

python - super(Foo, self) 和 super(Foo, self.__class__) 的区别?

javascript - 仅 GET 在使用 django-piston 的跨域 API 请求中工作

python - Django2.1 : Queryset ModelChoice in a ModelForm then save two forms

python - Django - TabularInline 没有添加按钮

python - 将类添加到 Django label_tag() 输出

python - 使用 Selenium 在 Python 中循环 XPath 元素位置

python - 如何为flask应用程序设置带有文本和图像的html?

python - 使用列表中的 max()/min() 获取返回的最大或最小项的索引

css - 如何改变CSS中按钮的背景颜色?

asp.net - 如何强制浏览器不存储HTML表单字段数据?