[英]How to make queryset equal to list in django webapp?
假設我在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 類型,所以我將查詢集轉換為列表,但在倒數第二行我 neet 使查詢集等於列表,但我得到了一個 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(...)
更多信息在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.