Home > database >  How to make queryset equal to list in django webapp?
How to make queryset equal to list in django webapp?

Time:10-19

Suppose that i have a model called "Test" in models.py, and the view function in views.py as follows:

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(...)

because the item in "the_query" is tuple type, but i need str type, so i convert the queryset to list, but at the second last row i neet make the queryset equal to the list, but i got an AttributeError, so i want to know is there any other way to achieve my demand?

CodePudding user response:

Without looking at the whole model & form definition, this might do:


    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(...)

More information here

  • Related