Search code examples
pythondjangodatabasedjango-querysetdjango-orm

How to use variable instead of giving field in filter queryset django


if I have a class like this:

class Name: field1 = ... field2 = ... ... I do not know what are the fields or model it should be given by user so key is going to be name of field in a model and value is what should I look for that. and base on some if I have to filter them with field1 or 2 and I have them from input in variables?

if name is an instance of Name and if key = field1 and value='example_to_look' ,I want name.objects.filter(key=value) not name.objects.filter(field1=value)

i want to use this on different classes and fields so if is not what I want. raw() always triggers a new query and doesn’t account for previous filtering but I need them all and I have to filter one by one!


Solution

  • we have to create a dict like do_filter={key:value} then use query_set =model.objects.all() then query_set.filter(**do_filter) for each one:) this way you can dynamically generate our query_set base on given variables.