在 Python Django 中,如何根据用户从组合框中的选择将字符字段分配给 SQL 中的列?
In Python Django, how do I assign a charfield to a column in SQL based on the user's selection from a combobox?
第一次来电。标题本质上是按问题描述的。我正在创建一个工作应用程序。他们正在请求一个表单字段,该字段可以动态分配给 SQL table 中的列,并从组合框中进行选择。
例如,假设我们有一个名为 "Groceries" 的 table。在 "Groceries" table 中,有 3 个列名为 "Dairy"、"Produce" 和 "Deli"。在网页上,有一个带有关联组合框的字符字段。组合框有 "Dairy"、"Produce" 和 "Deli" 作为选项。当用户在字符字段中提交文本时,它将填充用户从组合框中选择的数据库中的任何列。
我该怎么做?除非我问错了问题,否则我发现 Google 中还不存在的东西。
谢谢
这很简单。您使用带有 2 个字段的普通表单,一个是组合框,另一个是 char 字段:
class GroceryForm(forms.Form):
grocery_type = forms.ChoiceField(choices=(('dairy', 'Dairy'),
('produce', 'Produce'),
('deli', 'Deli')))
name = forms.CharField()
然后在views.py:
def blah_method(request):
form = GroceryForm(request.POST or None)
if form.is_valid():
grocery_type = form.cleaned_data['grocery_type']
if grocery_type == 'dairy':
result = Groceries.objects.create(dairy=form.cleaned_data['name'])
elif grocery_type == 'produce':
result = Groceries.objects.create(produce=form.cleaned_data['name'])
elif grocery_type == 'deli':
result = Groceries.objects.create(deli=form.cleaned_data['name'])
没有测试过,但你应该知道大概的意思。
第一次来电。标题本质上是按问题描述的。我正在创建一个工作应用程序。他们正在请求一个表单字段,该字段可以动态分配给 SQL table 中的列,并从组合框中进行选择。
例如,假设我们有一个名为 "Groceries" 的 table。在 "Groceries" table 中,有 3 个列名为 "Dairy"、"Produce" 和 "Deli"。在网页上,有一个带有关联组合框的字符字段。组合框有 "Dairy"、"Produce" 和 "Deli" 作为选项。当用户在字符字段中提交文本时,它将填充用户从组合框中选择的数据库中的任何列。
我该怎么做?除非我问错了问题,否则我发现 Google 中还不存在的东西。
谢谢
这很简单。您使用带有 2 个字段的普通表单,一个是组合框,另一个是 char 字段:
class GroceryForm(forms.Form):
grocery_type = forms.ChoiceField(choices=(('dairy', 'Dairy'),
('produce', 'Produce'),
('deli', 'Deli')))
name = forms.CharField()
然后在views.py:
def blah_method(request):
form = GroceryForm(request.POST or None)
if form.is_valid():
grocery_type = form.cleaned_data['grocery_type']
if grocery_type == 'dairy':
result = Groceries.objects.create(dairy=form.cleaned_data['name'])
elif grocery_type == 'produce':
result = Groceries.objects.create(produce=form.cleaned_data['name'])
elif grocery_type == 'deli':
result = Groceries.objects.create(deli=form.cleaned_data['name'])
没有测试过,但你应该知道大概的意思。