gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:01 25 4
gpt4 key购买 nike

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

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(...)
...

关于python - 选择形式的 Django 访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38011917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com