【问题标题】:How to make queryset equal to list in django webapp?如何使查询集等于 django webapp 中的列表?
【发布时间】: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


【解决方案1】:

如果不查看整个模型和表单定义,可能会这样做:


    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

【讨论】:

    猜你喜欢
    • 2016-02-19
    • 2021-04-06
    • 2010-10-15
    • 2012-04-19
    • 2017-11-28
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多