Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset with variable value

Tags:

I am writing dynamic filters in django for my database where I am using the below code where I have 2 variables(p_type,s_type):

        p_type=[]
        s_type=[]
        query = request.GET.get("q")
        p_type =request.GET.get("p_type")
        s_type = request.GET.get("s_type")
        #messages.add_message(request, messages.INFO, p_type)
        #messages.add_message(request, messages.INFO, s_type)
        if query:
            queryset_find = queryset_list.filter(
                Q(FP_Item__contains=query))
            context = {'object_list': queryset_find}
            return render(request, 'index.html', context)
        elif p_type:
            queryset_find = queryset_list.filter(
                Q(p_type__contains=s_type))
            context = {'object_list': queryset_find}
            return render(request, 'index.html', context)
        else:
            context = {'object_list': queryset}
            return render(request, 'index.html', context)

but django returns error at below line

Q(p_type__contains=s_type))

I have dynamic radio button where the value of p_type matches with my database but even though I am receiving the following error:

Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'p_type' into field. Choices are: ... (same choices which I am using with my database).

Isn't it doable with variable query ? Any other methods ?

model:

class RFP(models.Model):
    FP_Item = models.TextField(max_length=1500)
    P_63 = models.TextField(max_length=1000)
    P_64 = models.TextField(max_length=1000)
like image 847
İlkem Çetinkaya Avatar asked Apr 30 '18 10:04

İlkem Çetinkaya


1 Answers

If p_type holds the name of the field you want to query, then you can do:

elif p_type:
    kwargs = {
        '{}__contains'.format(p_type): s_type
    }
    queryset_find = queryset_list.filter(Q(**kwargs))
    ...
like image 197
Will Keeling Avatar answered Sep 28 '22 17:09

Will Keeling