Name | drf-complex-filter JSON |
Version |
2.0.0
JSON |
| download |
home_page | None |
Summary | Declarative filter for Django ORM |
upload_time | 2024-10-15 21:43:11 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.6 |
license | MIT License Copyright (c) 2020 Nikita Balobanov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
django
django-rest-framework
django-orm
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# Django Rest Framework Complex Filter
[![codecov](https://codecov.io/gh/kit-oz/drf-complex-filter/branch/main/graph/badge.svg?token=B6Z1LWBXOP)](https://codecov.io/gh/kit-oz/drf-complex-filter)
DRF filter for complex queries
## Installing
For installing use ``pip``
```bash
pip install drf-complex-filter
```
## Usage
Add ``ComplexQueryFilter`` to ``filter_backends``:
```python
from drf_complex_filter.filters import ComplexQueryFilter
class UserViewSet(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = [ComplexQueryFilter]
```
And get some records
```
GET /users?filters={"type":"operator","data":{"attribute":"first_name","operator":"=","value":"John"}}
```
## Filter operator
Operator may be one of three types
```python
# 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 operators
There are several basic operators in the package, but you are free to replace or expand this list.
### Existing operators
Operator label | Query operator
-------------- | --------------
Is | =
Is not | !=
Case-insensitive contains | *
Case-insensitive not contains | !
Greater | >
Greater than or is | >=
Less | <
Less than or is | <=
Value in list | in
Value not in list | not_in
Current user | me
Not current user | not_me
### Adding operators
First, create a class containing your operators. It should contain at least a "get_operators" method that returns a dictionary with your operators.
```python
class YourClassWithOperators:
def get_operators(self):
return {
"simple_operator": lambda f, v, r, m: Q(**{f"{f}": v}),
"complex_operator": self.complex_operator,
}
@staticmethod
def complex_operator(field: str, value=None, request=None, model: Model = None)
return Q(**{f"{field}": value})
```
Next, specify this class in the configuration.
```python
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 value
Sometimes 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.
```python
class YourClassWithFunctions:
def get_functions(self):
return {
"calculate_value": self.calculate_value,
}
@staticmethod
def calculate_value(request, model, my_arg):
return str(my_arg)
```
Then register this class in settings.
```python
COMPLEX_FILTER_SETTINGS = {
"VALUE_FUNCTIONS": [
"drf_complex_filter.functions.DateFunctions",
"path.to.your.module.YourClassWithFunctions",
],
}
```
And create an operator with a value like this:
```python
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 call
* __kwargs__ - a dictionary with arguments to pass to the method
The 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 it
## Subquery calculation
If 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 construction `RelatedModelName___` to your attribute name in operator,
After that, this construction is executed in a separate request.
```python
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 to
new_filter = {
"type": "operator",
"data": {
"attribute": "RelatedModelName_id",
"operator": "in",
"value": [2, 5, 9],
}
}
# and have two selects in DB:
# `select id from RelatedModelName where field_name = 'value_for_compare'`
# and `select * from MainTable where RelatedModelName_id in (2, 5, 9)`
```
Raw data
{
"_id": null,
"home_page": null,
"name": "drf-complex-filter",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.6",
"maintainer_email": null,
"keywords": "django, django-rest-framework, django-orm",
"author": null,
"author_email": "Nikita Balobanov <kit-oz@ya.ru>",
"download_url": "https://files.pythonhosted.org/packages/5f/c0/5d4c8da98965355cbe3949f733e5dc6501ab0549415f11431058d646fc7f/drf_complex_filter-2.0.0.tar.gz",
"platform": null,
"description": "# Django Rest Framework Complex Filter\n\n[![codecov](https://codecov.io/gh/kit-oz/drf-complex-filter/branch/main/graph/badge.svg?token=B6Z1LWBXOP)](https://codecov.io/gh/kit-oz/drf-complex-filter)\n\nDRF filter for complex queries\n\n## Installing\n\nFor installing use ``pip``\n\n```bash\n pip install drf-complex-filter\n```\n\n## Usage\n\nAdd ``ComplexQueryFilter`` to ``filter_backends``:\n\n```python\n\n from drf_complex_filter.filters import ComplexQueryFilter\n\n class UserViewSet(ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = [ComplexQueryFilter]\n\n```\n\nAnd get some records\n\n```\n\n GET /users?filters={\"type\":\"operator\",\"data\":{\"attribute\":\"first_name\",\"operator\":\"=\",\"value\":\"John\"}}\n```\n\n## Filter operator\n\nOperator may be one of three types\n\n```python\n\n # Will return Q(field_name=value_for_compare)\n operator_filter = {\n \"type\": \"operator\",\n \"data\": {\n \"attribute\": \"field_name\",\n \"operator\": \"=\",\n \"value\": \"value_for_compare\",\n }\n }\n\n # Will combine through AND all operators passed in \"data\"\n and_filter = {\n \"type\": \"and\",\n \"data\": []\n }\n\n # Will combine through OR all operators passed in \"data\"\n or_filter = {\n \"type\": \"or\",\n \"data\": []\n }\n\n```\n\n## Lookup operators\n\nThere are several basic operators in the package, but you are free to replace or expand this list.\n\n### Existing operators\n\nOperator label | Query operator\n-------------- | --------------\nIs | =\nIs not | !=\nCase-insensitive contains | *\nCase-insensitive not contains | !\nGreater | >\nGreater than or is | >=\nLess | <\nLess than or is | <=\nValue in list | in\nValue not in list | not_in\nCurrent user | me\nNot current user | not_me\n\n### Adding operators\n\nFirst, create a class containing your operators. It should contain at least a \"get_operators\" method that returns a dictionary with your operators.\n\n```python\nclass YourClassWithOperators:\n def get_operators(self):\n return {\n \"simple_operator\": lambda f, v, r, m: Q(**{f\"{f}\": v}),\n \"complex_operator\": self.complex_operator,\n }\n\n @staticmethod\n def complex_operator(field: str, value=None, request=None, model: Model = None)\n return Q(**{f\"{field}\": value})\n```\n\nNext, specify this class in the configuration.\n\n```python\nCOMPLEX_FILTER_SETTINGS = {\n \"COMPARISON_CLASSES\": [\n \"drf_complex_filter.comparisons.CommonComparison\",\n \"drf_complex_filter.comparisons.DynamicComparison\",\n \"path.to.your.module.YourClassWithOperators\",\n ],\n}\n```\n\nYou can now use these operators to filter models.\n\n## Computed value\n\nSometimes you need to get the value dynamically on the server side instead of writing it directly to the filter.\nTo do this, you can create a class containing the \"get_functions\" method.\n\n```python\nclass YourClassWithFunctions:\n def get_functions(self):\n return {\n \"calculate_value\": self.calculate_value,\n }\n\n @staticmethod\n def calculate_value(request, model, my_arg):\n return str(my_arg)\n```\n\nThen register this class in settings.\n\n```python\nCOMPLEX_FILTER_SETTINGS = {\n \"VALUE_FUNCTIONS\": [\n \"drf_complex_filter.functions.DateFunctions\",\n \"path.to.your.module.YourClassWithFunctions\",\n ],\n}\n```\n\nAnd create an operator with a value like this:\n\n```python\n\n value = {\n \"func\": \"name_of_func\",\n \"kwargs\": { \"my_arg\": \"value_of_my_arg\" },\n }\n\n operator_filter = {\n \"type\": \"operator\",\n \"data\": {\n \"attribute\": \"field_name\",\n \"operator\": \"=\",\n \"value\": value,\n }\n }\n```\n\nWhere:\n\n* __func__ - the name of the method to call\n* __kwargs__ - a dictionary with arguments to pass to the method\n\nThe 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 it\n\n## Subquery calculation\n\nIf you have one big query that needs to be done in chunks (not one big execution, just few small execution in related models),\nYou can add construction `RelatedModelName___` to your attribute name in operator,\nAfter that, this construction is executed in a separate request. \n\n```python\n\n operator_filter = {\n \"type\": \"operator\",\n \"data\": {\n \"attribute\": \"RelatedModelName___field_name\",\n \"operator\": \"=\",\n \"value\": \"value_for_compare\",\n }\n }\n \n # if this RelatedModelName.objects.filter(field_name=\"value_for_compare\") return objects with ids `2, 5, 9`,\n # so this `operator_filter` is equivalent to\n \n new_filter = {\n \"type\": \"operator\",\n \"data\": {\n \"attribute\": \"RelatedModelName_id\",\n \"operator\": \"in\",\n \"value\": [2, 5, 9],\n }\n }\n \n # and have two selects in DB:\n # `select id from RelatedModelName where field_name = 'value_for_compare'`\n # and `select * from MainTable where RelatedModelName_id in (2, 5, 9)`\n\n```\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2020 Nikita Balobanov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
"summary": "Declarative filter for Django ORM",
"version": "2.0.0",
"project_urls": {
"Homepage": "https://github.com/kit-oz/drf-complex-filter"
},
"split_keywords": [
"django",
" django-rest-framework",
" django-orm"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "14f8c3a059c144e0cf3e44c5be3386ee32e101a1f23b78bc3431c33b452e0dc0",
"md5": "0aa04973fab37196a5ca07f2c928db86",
"sha256": "4475d12fb885d13ad6f843eb1eccb9eb661c73685644a84fed3c5de5245368f9"
},
"downloads": -1,
"filename": "drf_complex_filter-2.0.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "0aa04973fab37196a5ca07f2c928db86",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6",
"size": 9121,
"upload_time": "2024-10-15T21:43:09",
"upload_time_iso_8601": "2024-10-15T21:43:09.445518Z",
"url": "https://files.pythonhosted.org/packages/14/f8/c3a059c144e0cf3e44c5be3386ee32e101a1f23b78bc3431c33b452e0dc0/drf_complex_filter-2.0.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "5fc05d4c8da98965355cbe3949f733e5dc6501ab0549415f11431058d646fc7f",
"md5": "9c3055c41bf088c589bf4deb169e903f",
"sha256": "49d63c4a2493f86496b34d67f36f68cc2df450f66a63be181bd2d16aa787bfeb"
},
"downloads": -1,
"filename": "drf_complex_filter-2.0.0.tar.gz",
"has_sig": false,
"md5_digest": "9c3055c41bf088c589bf4deb169e903f",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 17461,
"upload_time": "2024-10-15T21:43:11",
"upload_time_iso_8601": "2024-10-15T21:43:11.078414Z",
"url": "https://files.pythonhosted.org/packages/5f/c0/5d4c8da98965355cbe3949f733e5dc6501ab0549415f11431058d646fc7f/drf_complex_filter-2.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-15 21:43:11",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "kit-oz",
"github_project": "drf-complex-filter",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "drf-complex-filter"
}