Package: drf-complex-filter
Django Rest Framework Complex FilterDRF filter for complex queriesInstallingFor installing usepippipinstalldrf-complex-filterUsageAddComplexQueryFiltertofilter_backends:fromdrf_complex_filter.filtersimportComplexQueryFilterclassUserViewSet(ModelViewSet):queryset=User.objects.all()serializer_class=UserSerializerfilter_backends=[ComplexQueryFilter]And get some recordsGET /users?filters={"type":"operator","data":{"attribute":"first_name","operator":"=","value":"John"}}Filter operatorOperator may be one of three types# Will return Q(field_name=value_for_compare)operator_filter={"type":"operator","data":{"attribute":"field_name","operator":"=","value":"value_for_compare",}}# Will combine through AND all operators passed in "data"and_filter={"type":"and","data":[]}# Will combine through OR all operators passed in "data"or_filter={"type":"or","data":[]}Lookup operatorsThere are several basic operators in the package, but you are free to replace or expand this list.Existing operatorsOperator labelQuery operatorIs=Is not!=Case-insensitive contains*Case-insensitive not contains!Greater>Greater than or is>=Less<Less than or is<=Value in listinValue not in listnot_inCurrent usermeNot current usernot_meAdding operatorsFirst, create a class containing your operators. It should contain at least a "get_operators" method that returns a dictionary with your operators.classYourClassWithOperators:defget_operators(self):return{"simple_operator":lambdaf,v,r,m:Q(**{f"{f}":v}),"complex_operator":self.complex_operator,}@staticmethoddefcomplex_operator(field:str,value=None,request=None,model:Model=None)returnQ(**{f"{field}":value})Next, specify this class in the configuration.COMPLEX_FILTER_SETTINGS={"COMPARISON_CLASSES":["drf_complex_filter.comparisons.CommonComparison","drf_complex_filter.comparisons.DynamicComparison","path.to.your.module.YourClassWithOperators",],}You can now use these operators to filter models.Computed valueSometimes you need to get the value dynamically on the server side instead of writing it directly to the filter.
To do this, you can create a class containing the "get_functions" method.classYourClassWithFunctions:defget_functions(self):return{"calculate_value":self.calculate_value,}@staticmethoddefcalculate_value(request,model,my_arg):returnstr(my_arg)Then register this class in settings.COMPLEX_FILTER_SETTINGS={"VALUE_FUNCTIONS":["drf_complex_filter.functions.DateFunctions","path.to.your.module.YourClassWithFunctions",],}And create an operator with a value like this:value={"func":"name_of_func","kwargs":{"my_arg":"value_of_my_arg"},}operator_filter={"type":"operator","data":{"attribute":"field_name","operator":"=","value":value,}}Where:func- the name of the method to callkwargs- a dictionary with arguments to pass to the methodThe value will be calculated before being passed to the operator. That allows you to use the value obtained in this way with any operator that can correctly process itSubquery calculationIf you have one big query that needs to be done in chunks (not one big execution, just few small execution in related models),
You can add constructionRelatedModelName___to your attribute name in operator,
After that, this construction is executed in a separate request.operator_filter={"type":"operator","data":{"attribute":"RelatedModelName___field_name","operator":"=","value":"value_for_compare",}}# if this RelatedModelName.objects.filter(field_name="value_for_compare") return objects with ids `2, 5, 9`,# so this `operator_filter` is equivalent tonew_filter={"type":"operator","data":{"attribute":"RelatedModelNameField_id","operator":"in","value":[2,5,9],}}# and have two selects in DB:# `select id from RelatedModelNameField where field_name = 'value_for_compare'`# and `select * from MainTable where RelatedModelNameField_id in (2, 5, 9)`