There is a task to pass a variable to the Q object.

Request to the database:

data = Module.objects.filter(Q(plug_module='1') | Q(plug_module='2')) 

I consider 2 options 1) pass the variable select = "plug_module='1'" This variable is select = "plug_module='1'" to change. 2) send a completely ready request of type Q(plug_module='1') | Q(plug_module='2') Q(plug_module='1') | Q(plug_module='2') in Module.objects.filter()

 per = "Q(plug_module='1') | Q(plug_module='2')" data = Module.objects.filter(per) 

Is it possible to do so or not? The point is to automatically generate QuerySet requests depending on the data coming from the web.

  • It's not entirely clear what you want to achieve. Do you need to dynamically create a set of Q objects? Or filter any field by several options of values? - Chikiro
  • I need to dynamically create Q objects. - Andrey Bessonov

1 answer 1

If you want to get a sample containing all the specified values ​​of any field, you may be helped by field lookup in :

 Module.objects.filter(plug_module__in=['1', '2']) 

If complex generated filters with Q are needed:

 from operator import __or__ as OR from django.db.models import Q query_filters = [ Q(plug_module='1'), Q(plug_module='2') ] Module.objects.filter(reduce(OR, query_filters)) 

An example only for clarity, in fact it is meaningless, can be simplified to the first option.

UPD

 lookup = {'plug_module': ['1', '2']} filter_kwargs = {'%s__in' % field: value for field, value in lookup.items()} Module.objects.filter(**filter_kwargs) 
  • Thanks for the advice on field lookup in. The question was how to slip in 'Module.objects.filter (plug_module__in = [' 1 ',' 2 '])' instead of 'plug_module__in = [' 1 ',' 2 ']' to put a variable in which the plug_module will constantly change Andrey Bessonov
  • Paramters are passed to the filter as named arguments, you can pass them as a dictionary. Example in UPD. - Chikiro
  • Thank you so much, it helped a lot. I am new to this business :). only in the UPD code there is an error with - value in lookup.iteritems() did not work, changed to - value in lookup.items() and it all worked. thanks again! - Andrey Bessonov
  • My mistake, yes. This is the code for Python 2. Now I see that in the question tags you have Python 3. - Chikiro