djangoql-iplweb 0.20.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. djangoql_iplweb-0.20.0/LICENSE +21 -0
  2. djangoql_iplweb-0.20.0/PKG-INFO +590 -0
  3. djangoql_iplweb-0.20.0/README.md +554 -0
  4. djangoql_iplweb-0.20.0/djangoql/__init__.py +1 -0
  5. djangoql_iplweb-0.20.0/djangoql/admin.py +175 -0
  6. djangoql_iplweb-0.20.0/djangoql/ast.py +73 -0
  7. djangoql_iplweb-0.20.0/djangoql/exceptions.py +39 -0
  8. djangoql_iplweb-0.20.0/djangoql/lexer.py +178 -0
  9. djangoql_iplweb-0.20.0/djangoql/locale/de/LC_MESSAGES/django.mo +0 -0
  10. djangoql_iplweb-0.20.0/djangoql/locale/de/LC_MESSAGES/django.po +139 -0
  11. djangoql_iplweb-0.20.0/djangoql/locale/es/LC_MESSAGES/django.mo +0 -0
  12. djangoql_iplweb-0.20.0/djangoql/locale/es/LC_MESSAGES/django.po +135 -0
  13. djangoql_iplweb-0.20.0/djangoql/locale/fr/LC_MESSAGES/django.mo +0 -0
  14. djangoql_iplweb-0.20.0/djangoql/locale/fr/LC_MESSAGES/django.po +136 -0
  15. djangoql_iplweb-0.20.0/djangoql/locale/it/LC_MESSAGES/django.mo +0 -0
  16. djangoql_iplweb-0.20.0/djangoql/locale/it/LC_MESSAGES/django.po +135 -0
  17. djangoql_iplweb-0.20.0/djangoql/locale/ja/LC_MESSAGES/django.mo +0 -0
  18. djangoql_iplweb-0.20.0/djangoql/locale/ja/LC_MESSAGES/django.po +133 -0
  19. djangoql_iplweb-0.20.0/djangoql/locale/nl/LC_MESSAGES/django.mo +0 -0
  20. djangoql_iplweb-0.20.0/djangoql/locale/nl/LC_MESSAGES/django.po +137 -0
  21. djangoql_iplweb-0.20.0/djangoql/locale/pl/LC_MESSAGES/django.mo +0 -0
  22. djangoql_iplweb-0.20.0/djangoql/locale/pl/LC_MESSAGES/django.po +136 -0
  23. djangoql_iplweb-0.20.0/djangoql/locale/pt_BR/LC_MESSAGES/django.mo +0 -0
  24. djangoql_iplweb-0.20.0/djangoql/locale/pt_BR/LC_MESSAGES/django.po +135 -0
  25. djangoql_iplweb-0.20.0/djangoql/locale/ru/LC_MESSAGES/django.mo +0 -0
  26. djangoql_iplweb-0.20.0/djangoql/locale/ru/LC_MESSAGES/django.po +137 -0
  27. djangoql_iplweb-0.20.0/djangoql/locale/uk/LC_MESSAGES/django.mo +0 -0
  28. djangoql_iplweb-0.20.0/djangoql/locale/uk/LC_MESSAGES/django.po +135 -0
  29. djangoql_iplweb-0.20.0/djangoql/locale/zh_Hans/LC_MESSAGES/django.mo +0 -0
  30. djangoql_iplweb-0.20.0/djangoql/locale/zh_Hans/LC_MESSAGES/django.po +132 -0
  31. djangoql_iplweb-0.20.0/djangoql/parser.py +233 -0
  32. djangoql_iplweb-0.20.0/djangoql/parsetab.py +70 -0
  33. djangoql_iplweb-0.20.0/djangoql/queryset.py +47 -0
  34. djangoql_iplweb-0.20.0/djangoql/schema.py +510 -0
  35. djangoql_iplweb-0.20.0/djangoql/serializers.py +45 -0
  36. djangoql_iplweb-0.20.0/djangoql/static/djangoql/css/completion.css +85 -0
  37. djangoql_iplweb-0.20.0/djangoql/static/djangoql/css/completion.css.map +1 -0
  38. djangoql_iplweb-0.20.0/djangoql/static/djangoql/css/completion_admin.css +31 -0
  39. djangoql_iplweb-0.20.0/djangoql/static/djangoql/css/syntax_help.css +14 -0
  40. djangoql_iplweb-0.20.0/djangoql/static/djangoql/img/completion_example.png +0 -0
  41. djangoql_iplweb-0.20.0/djangoql/static/djangoql/img/completion_example_scaled.png +0 -0
  42. djangoql_iplweb-0.20.0/djangoql/static/djangoql/js/completion.js +2 -0
  43. djangoql_iplweb-0.20.0/djangoql/static/djangoql/js/completion.js.map +1 -0
  44. djangoql_iplweb-0.20.0/djangoql/static/djangoql/js/completion_admin.js +113 -0
  45. djangoql_iplweb-0.20.0/djangoql/static/djangoql/js/completion_admin_toggle.js +6 -0
  46. djangoql_iplweb-0.20.0/djangoql/static/djangoql/js/completion_admin_toggle_off.js +5 -0
  47. djangoql_iplweb-0.20.0/djangoql/templates/djangoql/error_message.html +7 -0
  48. djangoql_iplweb-0.20.0/djangoql/templates/djangoql/syntax_help.html +431 -0
  49. djangoql_iplweb-0.20.0/djangoql/views.py +83 -0
  50. djangoql_iplweb-0.20.0/djangoql_iplweb.egg-info/PKG-INFO +590 -0
  51. djangoql_iplweb-0.20.0/djangoql_iplweb.egg-info/SOURCES.txt +54 -0
  52. djangoql_iplweb-0.20.0/djangoql_iplweb.egg-info/dependency_links.txt +1 -0
  53. djangoql_iplweb-0.20.0/djangoql_iplweb.egg-info/requires.txt +9 -0
  54. djangoql_iplweb-0.20.0/djangoql_iplweb.egg-info/top_level.txt +1 -0
  55. djangoql_iplweb-0.20.0/pyproject.toml +133 -0
  56. djangoql_iplweb-0.20.0/setup.cfg +4 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 ivelum
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,590 @@
1
+ Metadata-Version: 2.4
2
+ Name: djangoql-iplweb
3
+ Version: 0.20.0
4
+ Summary: DjangoQL: Advanced search language for Django (iplweb fork with i18n)
5
+ Author-email: Denis Stebunov <support@ivelum.com>
6
+ Maintainer-email: Michał Pasternak <michal.dtz@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/iplweb/djangoql-iplweb
9
+ Project-URL: Repository, https://github.com/iplweb/djangoql-iplweb
10
+ Project-URL: Issues, https://github.com/iplweb/djangoql-iplweb/issues
11
+ Keywords: django,search,query-language,admin,autocomplete
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Natural Language :: English
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Framework :: Django :: 6.0
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: ply>=3.8
28
+ Provides-Extra: dev
29
+ Requires-Dist: ruff; extra == "dev"
30
+ Requires-Dist: pre-commit; extra == "dev"
31
+ Requires-Dist: bumpver; extra == "dev"
32
+ Requires-Dist: pytest; extra == "dev"
33
+ Requires-Dist: pytest-django; extra == "dev"
34
+ Requires-Dist: django>=4.2; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # DjangoQL
38
+
39
+ [![Tests](https://github.com/iplweb/djangoql-iplweb/actions/workflows/tests.yaml/badge.svg)](https://github.com/iplweb/djangoql-iplweb/actions/workflows/tests.yaml)
40
+ [![Python Version](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue)](https://github.com/iplweb/djangoql-iplweb)
41
+ [![Django Version](https://img.shields.io/badge/django-5.2%20%7C%206.0-blue)](https://github.com/iplweb/djangoql-iplweb)
42
+ [![License](https://img.shields.io/github/license/iplweb/djangoql-iplweb)](LICENSE)
43
+
44
+ Advanced search language for Django, with auto-completion. Supports logical operators, parenthesis, table joins, and works with any Django model. Tested on Python 3.10–3.14, Django 5.2 and 6.0. The auto-completion feature has been tested in Chrome, Firefox, Safari, IE9+.
45
+
46
+ > **This is a community fork.** `djangoql-iplweb` is a fork of the original
47
+ > [**DjangoQL** by ivelum](https://github.com/ivelum/djangoql) — install the
48
+ > upstream package from [`djangoql` on PyPI](https://pypi.org/project/djangoql/).
49
+ > This fork adds internationalization (i18n) of error messages and modernized
50
+ > packaging/tooling.
51
+ >
52
+ > These changes are offered back to the upstream project. **If the original
53
+ > maintainers merge them, please switch back to the upstream
54
+ > [`djangoql`](https://pypi.org/project/djangoql/) package** — this fork exists
55
+ > only to make the improvements available in the meantime, and will defer to
56
+ > upstream once they land there.
57
+ >
58
+ > It is published on PyPI as **`djangoql-iplweb`**, but the import name stays
59
+ > `djangoql` (so `INSTALLED_APPS` and `import djangoql` are unchanged).
60
+
61
+ See a video: [DjangoQL demo](https://youtu.be/oKVff4dHZB8)
62
+
63
+ ![DjangoQL auto-completion example](https://raw.githubusercontent.com/iplweb/djangoql-iplweb/master/djangoql/static/djangoql/img/completion_example_scaled.png)
64
+
65
+ ## Contents
66
+
67
+ - [Features](#features)
68
+ - [Supported versions](#supported-versions)
69
+ - [Installation](#installation)
70
+ - [Add it to your Django admin](#add-it-to-your-django-admin)
71
+ - [Using DjangoQL with the standard Django admin search](#using-djangoql-with-the-standard-django-admin-search)
72
+ - [Internationalization (i18n)](#internationalization-i18n)
73
+ - [Language reference](#language-reference)
74
+ - [DjangoQL Schema](#djangoql-schema)
75
+ - [Custom search fields](#custom-search-fields)
76
+ - [Can I use it outside of Django admin?](#can-i-use-it-outside-of-django-admin)
77
+ - [Using completion widget outside of Django admin](#using-completion-widget-outside-of-django-admin)
78
+
79
+ ## Features
80
+
81
+ - Python-like query syntax: logical operators (`and`, `or`), parenthesis, and the full set of comparison operators
82
+ - Searches across model relations via joins, e.g. `author.last_name = "Tolstoy"`
83
+ - Works with any Django model and drops into the Django admin with a single mixin
84
+ - Live auto-completion of model field names and values in the admin
85
+ - Configurable schema to restrict searchable models/fields and provide suggestion options
86
+ - Custom search fields for annotations and fully custom search logic
87
+ - Internationalized error messages with translation catalogs for 11 locales
88
+ - Usable outside the Django admin, including a standalone JavaScript completion widget
89
+
90
+ ## Supported versions
91
+
92
+ DjangoQL is tested against the following Django × Python combinations:
93
+
94
+ | Django | 3.10 | 3.11 | 3.12 | 3.13 | 3.14 |
95
+ |---------|:----:|:----:|:----:|:----:|:----:|
96
+ | 5.2 LTS | ✓ | ✓ | ✓ | ✓ | ✓ |
97
+ | 6.0 | — | — | ✓ | ✓ | ✓ |
98
+
99
+ ## Installation
100
+
101
+ Using [uv](https://docs.astral.sh/uv/) (recommended):
102
+
103
+ ``` shell
104
+ $ uv add djangoql-iplweb
105
+ ```
106
+
107
+ Using pip:
108
+
109
+ ``` shell
110
+ $ pip install djangoql-iplweb
111
+ ```
112
+
113
+ Add `'djangoql'` to `INSTALLED_APPS` in your `settings.py`:
114
+
115
+ ``` python
116
+ INSTALLED_APPS = [
117
+ ...
118
+ 'djangoql',
119
+ ...
120
+ ]
121
+ ```
122
+
123
+ ## Add it to your Django admin
124
+
125
+ Adding `DjangoQLSearchMixin` to your model admin will replace the standard Django search functionality with DjangoQL search. Example:
126
+
127
+ ``` python
128
+ from django.contrib import admin
129
+
130
+ from djangoql.admin import DjangoQLSearchMixin
131
+
132
+ from .models import Book
133
+
134
+
135
+ @admin.register(Book)
136
+ class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
137
+ pass
138
+ ```
139
+
140
+ ## Using DjangoQL with the standard Django admin search
141
+
142
+ DjangoQL will recognize if you have defined `search_fields` in your ModelAdmin class, and doing so will allow you to choose between an advanced search with DjangoQL and a standard Django search (as specified by search fields). Example:
143
+
144
+ ``` python
145
+ @admin.register(Book)
146
+ class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
147
+ search_fields = ('title', 'author__name')
148
+ ```
149
+
150
+ For the example above, a checkbox that controls search mode will appear near the search input. If the checkbox is on, then DjanqoQL search is used. There is also an option that controls if that checkbox is enabled by default - `djangoql_completion_enabled_by_default` (set to `True` by default):
151
+
152
+ ``` python
153
+ @admin.register(Book)
154
+ class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
155
+ search_fields = ('title', 'author__name')
156
+ djangoql_completion_enabled_by_default = False
157
+ ```
158
+
159
+ If you don't want two search modes, simply remove `search_fields` from your ModelAdmin class.
160
+
161
+ ## Internationalization (i18n)
162
+
163
+ User-facing error messages produced by the lexer, parser, schema validator and suggestions API are wrapped with `gettext_lazy` and ship with translation catalogs for several locales. The locale used at runtime follows Django's standard request-locale resolution (`LANGUAGE_CODE`, `LocaleMiddleware`, `Accept-Language`, etc.). If a translation is missing for a given message or locale, the original English string is used.
164
+
165
+ Supplied locales:
166
+
167
+ - `pl` - Polish (hand-written, native)
168
+ - `de` - German (auto-translated, review welcome)
169
+ - `fr` - French (auto-translated, review welcome)
170
+ - `es` - Spanish (auto-translated, review welcome)
171
+ - `ru` - Russian (auto-translated, review welcome)
172
+ - `uk` - Ukrainian (auto-translated, review welcome)
173
+ - `pt_BR` - Brazilian Portuguese (auto-translated, review welcome)
174
+ - `it` - Italian (auto-translated, review welcome)
175
+ - `nl` - Dutch (auto-translated, review welcome)
176
+ - `ja` - Japanese (auto-translated, review welcome)
177
+ - `zh_Hans` - Simplified Chinese (auto-translated, review welcome)
178
+
179
+ Each locale lives under `djangoql/locale/<code>/LC_MESSAGES/`. The `.mo` files are shipped in the package, so no extra build step is required at install time. To add a new language or improve an existing one, edit the corresponding `django.po` file and run `django-admin compilemessages` from the `djangoql/` directory (requires the `gettext` system package). PRs for native-speaker review of any auto-translated locale are very welcome.
180
+
181
+ ## Language reference
182
+
183
+ DjangoQL is shipped with comprehensive Syntax Help, which can be found in Django admin (see the Syntax Help link in auto-completion popup). Here's a quick summary:
184
+
185
+ DjangoQL's syntax resembles Python's, with some minor differences. Basically you just reference model fields as you would in Python code, then apply comparison and logical operators and parenthesis. DjangoQL is case-sensitive.
186
+
187
+ - model fields: exactly as they are defined in Python code. Access nested properties via `.`, for example `author.last_name`;
188
+ - strings can be enclosed in either double quotes or single quotes. To escape a quote, use `\"` for double quotes or `\'` for single quotes. You can also use single quotes to enclose strings containing double quotes, and vice versa;
189
+ - boolean and null values: `True`, `False`, `None`. Please note that they can be combined only with equality operators, so you can write `published = False or date_published = None`, but `published > False` will cause an error;
190
+ - logical operators: `and`, `or`;
191
+ - comparison operators: `=`, `!=`, `<`, `<=`, `>`, `>=`
192
+ - work as you expect;
193
+ - string-specific comparison operators: `startswith`, `not startswith`, `endswith`, `not endswith` - work as you expect. Test whether or not a string contains a substring: `~` and `!~` (translated into `__icontains` under the hood). Example: `name endswith "peace" or author.last_name ~ "tolstoy"`;
194
+ - date-specific comparison operators, compare by date part: `~` and `!~`. Example: `date_published ~ "2021-11"` - find books published in Nov, 2021;
195
+ - test a value vs. list: `in`, `not in`. Example: `pk in (2, 3)`.
196
+
197
+ ## DjangoQL Schema
198
+
199
+ Schema defines limitations - what you can do with a DjangoQL query. If you don't specify any schema, DjangoQL will provide a default schema for you. This will walk recursively through all model fields and relations and include everything it finds in the schema, so users would be able to search through everything. Sometimes this is not what you want, either due to DB performance or security concerns. If you'd like to limit search models or fields, you should define a schema. Here's an example:
200
+
201
+ ``` python
202
+ class UserQLSchema(DjangoQLSchema):
203
+ exclude = (Book,)
204
+ suggest_options = {
205
+ Group: ['name'],
206
+ }
207
+
208
+ def get_fields(self, model):
209
+ if model == Group:
210
+ return ['name']
211
+ return super(UserQLSchema, self).get_fields(model)
212
+
213
+
214
+ @admin.register(User)
215
+ class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
216
+ djangoql_schema = UserQLSchema
217
+ ```
218
+
219
+ In the example above we created a schema that does 3 things:
220
+
221
+ - excludes the Book model from search via `exclude` option. Instead of `exclude` you may also use `include`, which limits a search to listed models only;
222
+ - limits available search fields for Group model to only the `name` field , in the `.get_fields()` method;
223
+ - enables completion options for Group names via `suggest_options`.
224
+
225
+ An important note about `suggest_options`: it looks for the `choices` model field parameter first, and if it's not specified - it will synchronously pull all values for given model fields, so you should avoid large querysets there. If you'd like to define custom suggestion options, see below.
226
+
227
+ ## Custom search fields
228
+
229
+ Deeper search customization can be achieved with custom search fields. Custom search fields can be used to search by annotations, define custom suggestion options, or define fully custom search logic. In `djangoql.schema`, DjangoQL defines the following base field classes that you may subclass to define your own behavior:
230
+
231
+ - `IntField`
232
+ - `FloatField`
233
+ - `StrField`
234
+ - `BoolField`
235
+ - `DateField`
236
+ - `DateTimeField`
237
+ - `RelationField`
238
+
239
+ Here are examples for common use cases:
240
+
241
+ **Search by queryset annotations:**
242
+
243
+ ``` python
244
+ from djangoql.schema import DjangoQLSchema, IntField
245
+
246
+
247
+ class UserQLSchema(DjangoQLSchema):
248
+ def get_fields(self, model):
249
+ fields = super(UserQLSchema, self).get_fields(model)
250
+ if model == User:
251
+ fields += [IntField(name='groups_count')]
252
+ return fields
253
+
254
+
255
+ @admin.register(User)
256
+ class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
257
+ djangoql_schema = UserQLSchema
258
+
259
+ def get_queryset(self, request):
260
+ qs = super(CustomUserAdmin, self).get_queryset(request)
261
+ return qs.annotate(groups_count=Count('groups'))
262
+ ```
263
+
264
+ Let's take a closer look at what's happening in the example above. First, we add `groups_count` annotation to the queryset that is used by Django admin in the `CustomUserAdmin.get_queryset()` method. It would contain the number of groups a user belongs to. As our queryset now pulls this column, we can filter by it. It just needs to be included in the schema. In `UserQLSchema.get_fields()` we define a custom integer search field for the `User` model. Its name should match the name of the column in our queryset.
265
+
266
+ **Custom suggestion options**
267
+
268
+ ``` python
269
+ from djangoql.schema import DjangoQLSchema, StrField
270
+
271
+
272
+ class GroupNameField(StrField):
273
+ model = Group
274
+ name = 'name'
275
+ suggest_options = True
276
+
277
+ def get_options(self, search):
278
+ return super(GroupNameField, self)\
279
+ .get_options(search)\
280
+ .annotate(users_count=Count('user'))\
281
+ .order_by('-users_count')
282
+
283
+
284
+ class UserQLSchema(DjangoQLSchema):
285
+ def get_fields(self, model):
286
+ if model == Group:
287
+ return ['id', GroupNameField()]
288
+ return super(UserQLSchema, self).get_fields(model)
289
+
290
+
291
+ @admin.register(User)
292
+ class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
293
+ djangoql_schema = UserQLSchema
294
+ ```
295
+
296
+ In this example we've defined a custom GroupNameField that sorts suggestions for group names by popularity (no. of users in a group) instead of default alphabetical sorting.
297
+
298
+ **Custom search lookup**
299
+
300
+ DjangoQL base fields provide two basic methods that you can override to substitute either search column, search value, or both - `.get_lookup_name()` and `.get_lookup_value(value)`:
301
+
302
+ ``` python
303
+ class UserDateJoinedYear(IntField):
304
+ name = 'date_joined_year'
305
+
306
+ def get_lookup_name(self):
307
+ return 'date_joined__year'
308
+
309
+
310
+ class UserQLSchema(DjangoQLSchema):
311
+ def get_fields(self, model):
312
+ fields = super(UserQLSchema, self).get_fields(model)
313
+ if model == User:
314
+ fields += [UserDateJoinedYear()]
315
+ return fields
316
+
317
+
318
+ @admin.register(User)
319
+ class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
320
+ djangoql_schema = UserQLSchema
321
+ ```
322
+
323
+ In this example we've defined the custom `date_joined_year` search field for users, and used the built-in Django `__year` filter option in `.get_lookup_name()` to filter by date year only. Similarly you can use `.get_lookup_value(value)` hook to modify a search value before it's used in the filter.
324
+
325
+ **Fully custom search lookup**
326
+
327
+ `.get_lookup_name()` and `.get_lookup_value(value)` hooks cover many simple use cases, but sometimes they're not enough and you want a fully custom search logic. In such cases you can override main `.get_lookup()` method of a field. Example below demonstrates User `age` search:
328
+
329
+ ``` python
330
+ from djangoql.schema import DjangoQLSchema, IntField
331
+
332
+
333
+ class UserAgeField(IntField):
334
+ """
335
+ Search by given number of full years
336
+ """
337
+ model = User
338
+ name = 'age'
339
+
340
+ def get_lookup_name(self):
341
+ """
342
+ We'll be doing comparisons vs. this model field
343
+ """
344
+ return 'date_joined'
345
+
346
+ def get_lookup(self, path, operator, value):
347
+ """
348
+ The lookup should support with all operators compatible with IntField
349
+ """
350
+ if operator == 'in':
351
+ result = None
352
+ for year in value:
353
+ condition = self.get_lookup(path, '=', year)
354
+ result = condition if result is None else result | condition
355
+ return result
356
+ elif operator == 'not in':
357
+ result = None
358
+ for year in value:
359
+ condition = self.get_lookup(path, '!=', year)
360
+ result = condition if result is None else result & condition
361
+ return result
362
+
363
+ value = self.get_lookup_value(value)
364
+ search_field = '__'.join(path + [self.get_lookup_name()])
365
+ year_start = self.years_ago(value + 1)
366
+ year_end = self.years_ago(value)
367
+ if operator == '=':
368
+ return (
369
+ Q(**{'%s__gt' % search_field: year_start}) &
370
+ Q(**{'%s__lte' % search_field: year_end})
371
+ )
372
+ elif operator == '!=':
373
+ return (
374
+ Q(**{'%s__lte' % search_field: year_start}) |
375
+ Q(**{'%s__gt' % search_field: year_end})
376
+ )
377
+ elif operator == '>':
378
+ return Q(**{'%s__lt' % search_field: year_start})
379
+ elif operator == '>=':
380
+ return Q(**{'%s__lte' % search_field: year_end})
381
+ elif operator == '<':
382
+ return Q(**{'%s__gt' % search_field: year_end})
383
+ elif operator == '<=':
384
+ return Q(**{'%s__gte' % search_field: year_start})
385
+
386
+ def years_ago(self, n):
387
+ timestamp = now()
388
+ try:
389
+ return timestamp.replace(year=timestamp.year - n)
390
+ except ValueError:
391
+ # February 29
392
+ return timestamp.replace(month=2, day=28, year=timestamp.year - n)
393
+
394
+
395
+ class UserQLSchema(DjangoQLSchema):
396
+ def get_fields(self, model):
397
+ fields = super(UserQLSchema, self).get_fields(model)
398
+ if model == User:
399
+ fields += [UserAgeField()]
400
+ return fields
401
+
402
+
403
+ @admin.register(User)
404
+ class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
405
+ djangoql_schema = UserQLSchema
406
+ ```
407
+
408
+ ## Can I use it outside of Django admin?
409
+
410
+ Sure. You can add DjangoQL search functionality to any Django model using `DjangoQLQuerySet`:
411
+
412
+ ``` python
413
+ from django.db import models
414
+
415
+ from djangoql.queryset import DjangoQLQuerySet
416
+
417
+
418
+ class Book(models.Model):
419
+ name = models.CharField(max_length=255)
420
+ author = models.ForeignKey('auth.User')
421
+
422
+ objects = DjangoQLQuerySet.as_manager()
423
+ ```
424
+
425
+ With the example above you can perform a search like this:
426
+
427
+ ``` python
428
+ qs = Book.objects.djangoql(
429
+ 'name ~ "war" and author.last_name = "Tolstoy"'
430
+ )
431
+ ```
432
+
433
+ It returns a normal queryset, so you can extend it and reuse if necessary. The following code works fine:
434
+
435
+ ``` python
436
+ print(qs.count())
437
+ ```
438
+
439
+ Alternatively you can add DjangoQL search to any existing queryset, even if it's not an instance of DjangoQLQuerySet:
440
+
441
+ ``` python
442
+ from django.contrib.auth.models import User
443
+
444
+ from djangoql.queryset import apply_search
445
+
446
+ qs = User.objects.all()
447
+ qs = apply_search(qs, 'groups = None')
448
+ print(qs.exists())
449
+ ```
450
+
451
+ Schemas can be specified either as a queryset option, or passed to `.djangoql()` queryset method directly:
452
+
453
+ ``` python
454
+ class BookQuerySet(DjangoQLQuerySet):
455
+ djangoql_schema = BookSchema
456
+
457
+
458
+ class Book(models.Model):
459
+ ...
460
+
461
+ objects = BookQuerySet.as_manager()
462
+
463
+ # Now, Book.objects.djangoql() will use BookSchema by default:
464
+ Book.objects.djangoql('name ~ "Peace") # uses BookSchema
465
+
466
+ # Overriding default queryset schema with AnotherSchema:
467
+ Book.objects.djangoql('name ~ "Peace", schema=AnotherSchema)
468
+ ```
469
+
470
+ You can also provide schema as an option for `apply_search()`
471
+
472
+ ``` python
473
+ qs = User.objects.all()
474
+ qs = apply_search(qs, 'groups = None', schema=CustomSchema)
475
+ ```
476
+
477
+ ## Using completion widget outside of Django admin
478
+
479
+ The completion widget is not tightly coupled to Django admin, so you can easily use it outside of the admin if you want. The widget is [available on npm](https://www.npmjs.com/package/djangoql-completion) as a standalone package. See the source code and the docs in the [djangoql-completion](https://github.com/ivelum/djangoql-completion) repo on GitHub.
480
+
481
+ The completion widget is also bundled with the [djangoql-iplweb](https://pypi.org/project/djangoql-iplweb/) Python package on PyPI. If you're not using Webpack or another JavaScript bundler, you can use the pre-built version that ships with the Python package. Here is an example:
482
+
483
+ Template code, `completion_demo.html`:
484
+
485
+ ``` html
486
+ {% load static %}
487
+ <!DOCTYPE html>
488
+ <html lang="en">
489
+ <head>
490
+ <meta charset="UTF-8">
491
+ <title>DjangoQL completion demo</title>
492
+ <link rel="stylesheet" type="text/css" href="{% static 'djangoql/css/completion.css' %}" />
493
+ <script src="{% static 'djangoql/js/completion.js' %}"></script>
494
+ </head>
495
+ <body>
496
+
497
+ <form action="" method="get">
498
+ <p style="color: red">{{ error }}</p>
499
+ <textarea name="q" cols="40" rows="1" autofocus>{{ q }}</textarea>
500
+ </form>
501
+
502
+ <ul>
503
+ {% for item in search_results %}
504
+ <li>{{ item }}</li>
505
+ {% endfor %}
506
+ </ul>
507
+
508
+ <script>
509
+ DjangoQL.DOMReady(function () {
510
+ new DjangoQL({
511
+ // either JS object with a result of DjangoQLSchema(MyModel).as_dict(),
512
+ // or an URL from which this information could be loaded asynchronously
513
+ introspections: {{ introspections|safe }},
514
+
515
+ // css selector for query input or HTMLElement object.
516
+ // It should be a textarea
517
+ selector: 'textarea[name=q]',
518
+
519
+ // optional, you can provide URL for Syntax Help link here.
520
+ // If not specified, Syntax Help link will be hidden.
521
+ syntaxHelp: null,
522
+
523
+ // optional, enable textarea auto-resize feature. If enabled,
524
+ // textarea will automatically grow its height when entered text
525
+ // doesn't fit, and shrink back when text is removed. The purpose
526
+ // of this is to see full search query without scrolling, could be
527
+ // helpful for really long queries.
528
+ autoResize: true
529
+ });
530
+ });
531
+ </script>
532
+ </body>
533
+ </html>
534
+ ```
535
+
536
+ And in your `views.py`:
537
+
538
+ ``` python
539
+ import json
540
+
541
+ from django.contrib.auth.models import Group, User
542
+ from django.shortcuts import render_to_response
543
+ from django.views.decorators.http import require_GET
544
+
545
+ from djangoql.exceptions import DjangoQLError
546
+ from djangoql.queryset import apply_search
547
+ from djangoql.schema import DjangoQLSchema
548
+ from djangoql.serializers import DjangoQLSchemaSerializer
549
+
550
+
551
+ class UserQLSchema(DjangoQLSchema):
552
+ include = (User, Group)
553
+ suggest_options = {
554
+ Group: ['name'],
555
+ }
556
+
557
+
558
+ @require_GET
559
+ def completion_demo(request):
560
+ q = request.GET.get('q', '')
561
+ error = ''
562
+ query = User.objects.all().order_by('username')
563
+ if q:
564
+ try:
565
+ query = apply_search(query, q, schema=UserQLSchema)
566
+ except DjangoQLError as e:
567
+ query = query.none()
568
+ error = str(e)
569
+ # You may want to use SuggestionsAPISerializer and an additional API
570
+ # endpoint (see in djangoql.views) for asynchronous suggestions loading
571
+ introspections = DjangoQLSchemaSerializer().serialize(
572
+ UserQLSchema(query.model),
573
+ )
574
+ return render_to_response('completion_demo.html', {
575
+ 'q': q,
576
+ 'error': error,
577
+ 'search_results': query,
578
+ 'introspections': json.dumps(introspections),
579
+ })
580
+ ```
581
+
582
+ ## Supported by
583
+
584
+ This fork is graciously supported and maintained by **[iplweb](https://www.iplweb.pl/)**.
585
+
586
+ <a href="https://www.iplweb.pl/"><img src="https://avatars.githubusercontent.com/iplweb" alt="iplweb" width="96" /></a>
587
+
588
+ ## License
589
+
590
+ MIT