2

i want to change the filtering field dynamically.

i have a model named Product and fields are title and code

class Product(models.Model):
    title = models.CharField(max_length=50)
    code = models.CharField(max_length=50)

my filtering field will be dynamic in views like this

def filter(request):

    search_choices = {
        '1': 'title__icontains',
        '2': 'code__icontains',
        }

    col_num = request.GET.get("col_num")
    value = request.GET.get("value")

    search_field = search_choices.get("col_num")

    qs = Product.objects.filter(search_field=value)

    ........

here the variable search_field is always dynamic ... so how can i achieve this

coder
  • 451
  • 2
  • 7
  • 13
  • 1
    Possible duplicate of [In Django, how does one filter a QuerySet with dynamic field lookups?](https://stackoverflow.com/questions/310732/in-django-how-does-one-filter-a-queryset-with-dynamic-field-lookups) – ramganesh Apr 17 '18 at 10:18
  • @ramganesh thankyou for your answer – coder Apr 17 '18 at 11:17

1 Answers1

6

You can achieve this by passing argument as dictionary:

value = request.GET.get("value")
search_field = search_choices.get("col_num")
qs = Product.objects.filter(**{search_field: value})
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100