【发布时间】:2021-12-06 03:01:30
【问题描述】:
假设我在 models.py 中有一个名为“Test”的模型, 以及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,所以我想知道有没有其他方法可以满足我的需求?
【问题讨论】:
-
修改倒数第二行:
[the_list[x][0] for x in range(0, the_length)]
标签: python django django-queryset