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)
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))
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With