2012-08-14 70 views
2

我想就如何使这个更通用的,如果可能的一些指导:的Python +制作功能更通用

def get_industry_choices(self): 
    industries = Industry.objects.all().order_by('name') 
    ind_arr = [(ind.id, ind.name) for ind in industries] 

    return ind_arr 

基本上这个函数会返回choices预期为forms.ChoiceField。我需要在一些地方做到这一点,并希望使功能更上一层楼。我知道如何让industries = Industry.objects.all().order_by('name')成为通用的,但第二部分是我不确定的。在创建元组时,它有(ind.id, ind.name)ind.name可以是任何值,具体取决于传入的模型(模型中可能不总是有name)。

我试着在一些地方在这读了,包括:

Passing functions with arguments to another function in Python?

上述资源展示了如何使用传递函数它做的,但似乎有点矫枉过正?如果我必须传递一个函数作为参数,那么通过多一个函数使它更具通用性又有什么意义呢?

[编辑]

基本上我想制作一些与此类似:

TITLE_CHOICES=(
    (1, 'Mr.'), 
    (2, 'Ms.'), 
    (3, 'Mrs.'), 
    (4, 'Dr.'), 
    (5, 'Prof.'), 
    (6, 'Rev.'), 
    (7, 'Other'), 
) 

这样算下来forms.ChoiceField当我在TITLE_CHOICES通过例如,作为可能的选择。第一个值是我在提交表单时获得的值,第二个值是用户在表单上看到的值。我希望能够用任何模型以编程方式创建此模型,我传入模型名称和上面示例中的一个字段name。我想创建这个元组,使其成为(id, name)。但name可以用任何不同的模型替换...

+0

+1为寻找答案第一 – msw 2012-08-14 04:32:27

+0

的问题是什么? – 2012-08-14 04:35:30

+0

对不起,如果有困惑......但想知道是否有一些我错过了,试图使上述功能尽可能通用。 – KVISH 2012-08-14 04:36:53

回答

2

很难说从你的问题,但我认为你缺少的是getattr()。例如

ind = something() 
for field in ['id', 'name']: 
    print getattr(ind, field) 
+0

这工作!谢谢。我以前从未使用'getattr'方法。 – KVISH 2012-08-14 04:54:38

+0

不要创建新的标签,如'gimme-codez'。只标记问题。 – casperOne 2012-08-14 18:11:05

0

也许这会有所帮助:

from some_app.models import SomeModel 


def generate_choices(model, order=None *args): 
    choices = model.objects 
    if order: 
     choices = choices.order_by(order) 
    return choices.values_list('pk', *args) 


class MyForm(forms.Form): 
    my_choice_field = CharField(max_length=1, 
           choices=generate_choices(SomeModel, 'name')) 
    other_choice_field = CharField(max_length=1, 
            choices=generate_choices(SomeModel, 'city', 'state')) 
1

事实上,Django的已经为这个快捷方式:values_list

Industry.objects.all().values_list('id', 'name') 

fields = ['id', 'name'] 
Industry.objects.all().values_list(*fields) 
+0

这是一个更清洁的解决方案,但仅限于此特定用例。所以我会保留另一个作为答案,因为它会在大多数其他情况下工作。 – KVISH 2012-08-14 14:16:05