is there any way we can filter the queryset dynamically i.e we have a two string value from the url and search the model where first string is an attribute of the model and get all the objects containing second string in that particular attribute
Asked
Active
Viewed 402 times
0
-
Use [**django-filter**](https://django-filter.readthedocs.io/en/stable/) package – JPG May 29 '20 at 07:13
-
If you need just one attribute, then django-filter will be a too complex solution for a simple problem. But if you can get multiple attributes at a time then you can go ahead with django-filter – Arvind Kumar May 29 '20 at 07:25
-
Does this answer your question? [Dynamic filter in Django](https://stackoverflow.com/questions/47182481/dynamic-filter-in-django) – A.Raouf May 29 '20 at 14:31
1 Answers
0
Hi you just need to follow this solution and adapt it to your case
Model.objects.values('attribute', 'id') # using '.values'
[{'attribute': 'some attribute', 'id': 1 }, {'attribute': 'some 3', 'id': 2}, {'attribute': 'something', 'id': 3}, {'attribute': 'some some', 'id': 4}] # returns list of dictionaries
Filter or search the list of dictionaries with your "second string" and make a new query with the ids. You can adapt this one
Model.objects.filter(id__in=object_ids)
or use this solution
filterExpresion = attribute+'__contains'
dynamicFilter = {filterExpresion: secondString}
Model.objects.filter(**dynamicFilter)

Rafael Arias
- 13
- 3