我有一个类 GroupAdminForm 用于扩展 Django 中的组管理页面。有两个字段,selected_to_change 和 print_name。我打算做的是在 "selected_to_change" 中选择一列并在 "print_name" 中输入一个字符名称,以便进行如下查询:
UPDATE "annotation"
SET print_name= "value of print_name"
WHERE id = "value of selected_to_change";
这是 GroupAdminForm:
class GroupAdminForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(queryset=User.objects.all(),
widget=FilteredSelectMultiple('Users', False),
required=False)
select_to_change = forms.ModelChoiceField(queryset=Annotation.objects.all(), required=False)
print_name = forms.CharField(required=False)
class Meta:
model = Group
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
if instance is not None:
initial = kwargs.get('initial', {})
initial['users'] = instance.user_set.all()
initial['locations'] = instance.c_locations.all()
kwargs['initial'] = initial
super(GroupAdminForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
group = super(GroupAdminForm, self).save(commit=commit)
if commit:
group.user_set = self.cleaned_data['users']
else:
old_save_m2m = self.save_m2m
def new_save_m2m():
old_save_m2m()
group.user_set = self.cleaned_data['users']
self.save_m2m = new_save_m2m
return group
如何从 CharField 和 ModelChoiceField 获取值以在方法 save() 中进行此类查询?谢谢。