如何使查询集等于 django webapp 中的列表?
How to make queryset equal to list in django webapp?
假设我在 models.py 中有一个名为“测试”的模型,
views.py中的视图函数如下:
def app_view(request):
if request.method == 'POST':
form = AppForm(request.POST)
if form.is_valid:
...
else:
form = AppForm()
the_query = Test.objects.all().values_list('test_field')
the_list = list(the_query)
the_length = len(the_list)
form.fields['test_field'].queryset = [the_list[x] for x in range(0,the_length)]
return render(...)
因为“the_query”里面的项目是元组类型,但我需要str类型,所以我将查询集转换为列表,但在倒数第二行我需要使查询集等于列表,但是我得到了一个AttributeError,所以我想知道有没有其他方法可以实现我的需求?
在不查看整个模型和表单定义的情况下,这可能会:
def app_view(request):
if request.method == 'POST':
form = AppForm(request.POST)
if form.is_valid:
...
else:
form = AppForm()
form.fields['test_field'].queryset = Test.objects.all()
return render(...)
更多信息here
假设我在 models.py 中有一个名为“测试”的模型, views.py中的视图函数如下:
def app_view(request):
if request.method == 'POST':
form = AppForm(request.POST)
if form.is_valid:
...
else:
form = AppForm()
the_query = Test.objects.all().values_list('test_field')
the_list = list(the_query)
the_length = len(the_list)
form.fields['test_field'].queryset = [the_list[x] for x in range(0,the_length)]
return render(...)
因为“the_query”里面的项目是元组类型,但我需要str类型,所以我将查询集转换为列表,但在倒数第二行我需要使查询集等于列表,但是我得到了一个AttributeError,所以我想知道有没有其他方法可以实现我的需求?
在不查看整个模型和表单定义的情况下,这可能会:
def app_view(request):
if request.method == 'POST':
form = AppForm(request.POST)
if form.is_valid:
...
else:
form = AppForm()
form.fields['test_field'].queryset = Test.objects.all()
return render(...)
更多信息here