Skip to main content
 首页 » 编程设计

python之选择形式的 Django 访问对象属性

2024年10月17日38飞鱼

我有一个选择表单,允许用户选择分配给他们的特定范围的员工。

class ReservationBookingForm(forms.Form): 
    employee = forms.ModelChoiceField( 
        queryset = Employee.objects.none(), 
        #widget = forms.RadioSelect, 
        empty_label = None,  
        required = True, 
        label = '', 
        widget=forms.Select(attrs={'class':'input-lg text-center'}), 
        ) 
    def __init__(self, rangeId, *args, **kwargs): 
        super(ReservationBookingForm, self).__init__(*args, **kwargs) 
        self.fields['employee'].queryset = Employee.objects.filter(Q(range = rangeId ) | Q(range = 'B')) 

我想要做的是将选择选项显示为 Employee.first_name 和 Employee.last_name。我真的不想通过 unicode 方法来做到这一点。

有办法吗?

我得到的(没有 unicode)是:

option1 - Employee Object 
option2 - Employee Object 

我想要什么:

option1 - John Doe 
option2 - Jack Doe 

但我想在不覆盖 unicode 方法的情况下实现这一目标。

请您参考如下方法:

最后ModelChoiceField部分:

The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it.

在你的情况下:

from django.forms import ModelChoiceField 
 
class MyModelChoiceField(ModelChoiceField): 
    def label_from_instance(self, obj): 
        return "{} {}".format(obj.first_name, obj.last_name) 
 
class ReservationBookingForm(forms.Form): 
    employee = MyModelChoiceField(...) 
    ...