5

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)
6
  • What error do you get? Commented Apr 30, 2018 at 10:28
  • Shouln't you use p__type__contains? Commented Apr 30, 2018 at 10:29
  • I get the error FieldError at /fp/ Cannot resolve keyword 'p_type' into field. Choices are: P_63, P_64 etc.. Commented Apr 30, 2018 at 10:47
  • I wrote as p_type not p__type. Should I change ? Commented Apr 30, 2018 at 10:48
  • please show your model. I assume, you filter not the queryset, that you need. Commented Apr 30, 2018 at 12:35

1 Answer 1

4

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))
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

I also found another solution that can be used as per below: queryset_find = queryset_list.filter( Q(**{p_type: s_type}))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.