### Install DjangoQL using pip
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Install the djangoql package using pip. This is the first step to integrate DjangoQL into your project.
```shell
pip install djangoql
```
--------------------------------
### DjangoQL String Comparison Example
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Demonstrates string comparison using 'endswith' and the '~' operator for substring matching (icontains).
```djangoql
name endswith "peace" or author.last_name ~ "tolstoy"
```
--------------------------------
### Perform Search with DjangoQLQuerySet
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Example of performing a search query using the DjangoQLQuerySet manager. The result is a standard Django queryset that can be further manipulated.
```python
qs = Book.objects.djangoql(
'name ~ "war" and author.last_name = "Tolstoy"'
)
print(qs.count())
```
--------------------------------
### Django View for Completion Widget Demo
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
This Python view handles GET requests, processes the search query using `apply_search` with a custom `UserQLSchema`, and renders the completion demo template. It includes error handling for `DjangoQLError`.
```python
import json
from django.contrib.auth.models import Group, User
from django.shortcuts import render_to_response
from django.views.decorators.http import require_GET
from djangoql.exceptions import DjangoQLError
from djangoql.queryset import apply_search
from djangoql.schema import DjangoQLSchema
from djangoql.serializers import DjangoQLSchemaSerializer
class UserQLSchema(DjangoQLSchema):
include = (User, Group)
suggest_options = {
Group: ['name'],
}
@require_GET
def completion_demo(request):
q = request.GET.get('q', '')
error = ''
query = User.objects.all().order_by('username')
if q:
try:
query = apply_search(query, q, schema=UserQLSchema)
except DjangoQLError as e:
query = query.none()
error = str(e)
# You may want to use SuggestionsAPISerializer and an additional API
# endpoint (see in djangoql.views) for asynchronous suggestions loading
introspections = DjangoQLSchemaSerializer().serialize(
UserQLSchema(query.model),
)
return render_to_response('completion_demo.html', {
'q': q,
'error': error,
'search_results': query,
'introspections': json.dumps(introspections),
})
```
--------------------------------
### Custom Suggestion Options for Group Names
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Define custom suggestion options for fields, sorting them by custom criteria. This example sorts group names by the number of associated users.
```python
from djangoql.schema import DjangoQLSchema, StrField
from django.db.models import Count
class GroupNameField(StrField):
model = Group
name = 'name'
suggest_options = True
def get_options(self, search):
return super(GroupNameField, self)
.get_options(search)
.annotate(users_count=Count('user'))
.order_by('-users_count')
class UserQLSchema(DjangoQLSchema):
def get_fields(self, model):
if model == Group:
return ['id', GroupNameField()]
return super(UserQLSchema, self).get_fields(model)
@admin.register(User)
class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
djangoql_schema = UserQLSchema
```
--------------------------------
### Integrate Custom Schema with Django Admin
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Register a custom DjangoQL schema with a Django admin model to enable custom search fields. This example shows how to add the UserAgeField to the User model's schema.
```python
class UserQLSchema(DjangoQLSchema):
def get_fields(self, model):
fields = super(UserQLSchema, self).get_fields(model)
if model == User:
fields += [UserAgeField()]
return fields
@admin.register(User)
class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
djangoql_schema = UserQLSchema
```
--------------------------------
### Custom Search Lookup for Date Joined Year
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Override DjangoQL's default lookup behavior to target specific date parts or custom fields. This example creates a field to search by the year of 'date_joined'.
```python
from djangoql.schema import DjangoQLSchema, IntField
class UserDateJoinedYear(IntField):
name = 'date_joined_year'
def get_lookup_name(self):
return 'date_joined__year'
class UserQLSchema(DjangoQLSchema):
def get_fields(self, model):
```
--------------------------------
### Search by Related Models in DjangoQL
Source: https://github.com/ivelum/djangoql/blob/master/djangoql/templates/djangoql/syntax_help.html
Use the dot (.) separator to access fields in related models. For example, 'groups.name' searches the 'name' field of the 'groups' related model. To find records linked to any related model, compare the model to None.
```djangoql
groups.name in ("Marketing", "Support")
```
```djangoql
groups = None
```
```djangoql
groups != None
```
--------------------------------
### Add DjangoQL to INSTALLED_APPS
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Add 'djangoql' to your project's INSTALLED_APPS in settings.py to enable DjangoQL functionality.
```python
INSTALLED_APPS = [
...
'djangoql',
...
]
```
--------------------------------
### Initialize DjangoQL Completion
Source: https://github.com/ivelum/djangoql/blob/master/test_project/core/templates/completion_demo.html
Initializes DjangoQL with introspection data and configuration for the query input. Use this to enable autocompletion and other features for a textarea element.
```javascript
DjangoQL.DOMReady(function () {
DjangoQL.init({
// either JS object with a result of DjangoQLSchema(MyModel).as_dict(),
// or an URL from which this information could be loaded asynchronously
introspections: {{ introspections|safe }},
// css selector for query input. It should be a textarea
selector: 'textarea[name=q]',
// optional, you can provide URL for Syntax Help link here.
// If not specified, Syntax Help link will be hidden.
syntaxHelp: null,
// optional, enable textarea auto-resize feature. If enabled,
// textarea will automatically grow its height when entered text
// doesn't fit, and shrink back when text is removed. The purpose
// of this is to see full search query without scrolling, could be
// helpful for really long queries.
autoResize: true
});
});
```
--------------------------------
### HTML Template for DjangoQL Completion Widget
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
This HTML template integrates the djangoql completion widget into a form. It includes necessary CSS and JavaScript, and configures the widget with introspection data and options.
```html
{% load static %}
DjangoQL completion demo
{% for item in search_results %}
{{ item }}
{% endfor %}
```
--------------------------------
### Applying Search with a Custom Schema
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Shows how to use the `apply_search` function to filter a queryset with a custom schema. This is useful for applying complex search logic defined in a specific schema.
```python
qs = User.objects.all()
qs = apply_search(qs, 'groups = None', schema=CustomSchema)
```
--------------------------------
### Default and Overridden Schema Usage in Django ORM
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Demonstrates how to set a default schema for a model's manager and how to override it for specific queries. Ensure the model has a custom manager with djangoql support.
```python
djangoql_schema = BookSchema
class Book(models.Model):
...
objects = BookQuerySet.as_manager()
# Now, Book.objects.djangoql() will use BookSchema by default:
Book.objects.djangoql('name ~ "Peace") # uses BookSchema
# Overriding default queryset schema with AnotherSchema:
Book.objects.djangoql('name ~ "Peace", schema=AnotherSchema)
```
--------------------------------
### Integrate DjangoQLSearchMixin with ModelAdmin
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Inherit from DjangoQLSearchMixin in your ModelAdmin class to replace the standard Django search with DjangoQL.
```python
from django.contrib import admin
from djangoql.admin import DjangoQLSearchMixin
from .models import Book
@admin.register(Book)
class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
pass
```
--------------------------------
### Apply DjangoQL Search to Existing Queryset
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Integrate DjangoQL search into an existing Django queryset using the apply_search function. This is useful when you don't want to modify the model's default manager.
```python
from django.contrib.auth.models import User
from djangoql.queryset import apply_search
qs = User.objects.all()
qs = apply_search(qs, 'groups = None')
print(qs.exists())
```
--------------------------------
### Enable DjangoQL with search_fields
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Define search_fields in your ModelAdmin to enable a choice between DjangoQL and standard Django search. A checkbox will appear to switch modes.
```python
@admin.register(Book)
class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
search_fields = ('title', 'author__name')
```
--------------------------------
### Combining Search Conditions with Logical Operators
Source: https://github.com/ivelum/djangoql/blob/master/djangoql/templates/djangoql/syntax_help.html
Combine multiple search conditions using 'and' or 'or'. Use parentheses for complex queries involving both operators to ensure correct precedence.
```text
first_name = "John" and date_joined >= "2017-01-01"
```
```text
is_superuser = True or is_staff = True
```
```text
(is_superuser = True or is_staff = True) and date_joined > "2017-01-01"
```
--------------------------------
### DjangoQL Comparison Operators
Source: https://github.com/ivelum/djangoql/blob/master/djangoql/templates/djangoql/syntax_help.html
DjangoQL supports a variety of comparison operators for filtering data. Note that '~' and '!~' apply to string and date/datetime fields, while 'startswith', 'endswith', and their negations apply only to strings. Boolean and null values only work with '=' and '!='.
```djangoql
first_name = "John"
```
```djangoql
id != 42
```
```djangoql
email ~ "@gmail.com"
```
```djangoql
username !~ "test"
```
```djangoql
last_name startswith "do"
```
```djangoql
last_name not startswith "do"
```
```djangoql
last_name endswith "oe"
```
```djangoql
last_name not endswith "oe"
```
```djangoql
date_joined > "2017-02-28"
```
```djangoql
id >= 9000
```
```djangoql
id < 9000
```
```djangoql
last_login <= "2017-02-28 14:53"
```
```djangoql
first_name in ("John", "Jack", "Jason")
```
```djangoql
id not in (42, 9000)
```
--------------------------------
### Use DjangoQLQuerySet for Model Search
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Extend a Django model to use DjangoQLQuerySet as its manager for enabling direct DjangoQL searches. This allows performing complex searches directly on the model's objects.
```python
from django.db import models
from djangoql.queryset import DjangoQLQuerySet
class Book(models.Model):
name = models.CharField(max_length=255)
author = models.ForeignKey('auth.User')
objects = DjangoQLQuerySet.as_manager()
```
--------------------------------
### Define Custom DjangoQL Schema
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Exclude models, limit fields, and enable suggestions for specific models. Use 'exclude' or 'include' to control model visibility. Define specific fields for a model in 'get_fields'. Enable completion options with 'suggest_options'.
```python
class UserQLSchema(DjangoQLSchema):
exclude = (Book,)
suggest_options = {
Group: ['name'],
}
def get_fields(self, model):
if model == Group:
return ['name']
return super(UserQLSchema, self).get_fields(model)
@admin.register(User)
class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
djangoql_schema = UserQLSchema
```
--------------------------------
### Basic Search Condition
Source: https://github.com/ivelum/djangoql/blob/master/djangoql/templates/djangoql/syntax_help.html
A fundamental search condition includes a field, comparison operator, and value.
```text
first_name = "John"
```
```text
date_joined >= "2017-01-01"
```
```text
is_superuser = True
```
```text
first_name in ("John", "Jack", "Jason")
```
--------------------------------
### Search by Queryset Annotations in DjangoQL
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Add custom annotated fields to your schema to allow searching by calculated values. Ensure the annotation is present in the queryset and then define a corresponding field in the schema.
```python
from djangoql.schema import DjangoQLSchema, IntField
from django.db.models import Count
class UserQLSchema(DjangoQLSchema):
def get_fields(self, model):
fields = super(UserQLSchema, self).get_fields(model)
if model == User:
fields += [IntField(name='groups_count')]
return fields
@admin.register(User)
class CustomUserAdmin(DjangoQLSearchMixin, UserAdmin):
djangoql_schema = UserQLSchema
def get_queryset(self, request):
qs = super(CustomUserAdmin, self).get_queryset(request)
return qs.annotate(groups_count=Count('groups'))
```
--------------------------------
### Define Custom UserAgeField for DjangoQL
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Implement a custom search field for user age by overriding get_lookup_name and get_lookup. This field searches based on the 'date_joined' model field and supports various comparison operators.
```python
from djangoql.schema import DjangoQLSchema, IntField
class UserAgeField(IntField):
"""
Search by given number of full years
"""
model = User
name = 'age'
def get_lookup_name(self):
"""
We'll be doing comparisons vs. this model field
"""
return 'date_joined'
def get_lookup(self, path, operator, value):
"""
The lookup should support with all operators compatible with IntField
"""
if operator == 'in':
result = None
for year in value:
condition = self.get_lookup(path, '=', year)
result = condition if result is None else result | condition
return result
elif operator == 'not in':
result = None
for year in value:
condition = self.get_lookup(path, '!=', year)
result = condition if result is None else result & condition
return result
value = self.get_lookup_value(value)
search_field = '__'.join(path + [self.get_lookup_name()])
year_start = self.years_ago(value + 1)
year_end = self.years_ago(value)
if operator == '=':
return (
Q(**{'%s__gt' % search_field: year_start}) &
Q(**{'%s__lte' % search_field: year_end})
)
elif operator == '!=':
return (
Q(**{'%s__lte' % search_field: year_start}) |
Q(**{'%s__gt' % search_field: year_end})
)
elif operator == '>':
return Q(**{'%s__lt' % search_field: year_start})
elif operator == '>=':
return Q(**{'%s__lte' % search_field: year_end})
elif operator == '<':
return Q(**{'%s__gt' % search_field: year_end})
elif operator == '<=':
return Q(**{'%s__gte' % search_field: year_start})
def years_ago(self, n):
timestamp = now()
try:
return timestamp.replace(year=timestamp.year - n)
except ValueError:
# February 29
return timestamp.replace(month=2, day=28, year=timestamp.year - n)
```
--------------------------------
### DjangoQL Value Types
Source: https://github.com/ivelum/djangoql/blob/master/djangoql/templates/djangoql/syntax_help.html
DjangoQL supports various data types for query values, including strings, integers, floats, booleans, dates, datetimes, and null. Ensure correct formatting and case sensitivity for boolean and null values.
```djangoql
"this is a string"
```
```djangoql
'another string'
```
```djangoql
"this is a string with \"quoted\" text"
```
```djangoql
'this is a string with \'quoted\' text'
```
```djangoql
42
```
```djangoql
0
```
```djangoql
-9000
```
```djangoql
3.14
```
```djangoql
-0.5
```
```djangoql
5.972e24
```
```djangoql
True
```
```djangoql
False
```
```djangoql
"2017-02-28"
```
```djangoql
"2017-02-28 14:53"
```
```djangoql
"2017-02-28 14:53:07"
```
```djangoql
None
```
--------------------------------
### Control Default DjangoQL Search Mode
Source: https://github.com/ivelum/djangoql/blob/master/README.rst
Set djangoql_completion_enabled_by_default to False in your ModelAdmin to disable DjangoQL search by default. It defaults to True.
```python
@admin.register(Book)
class BookAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
search_fields = ('title', 'author__name')
djangoql_completion_enabled_by_default = False
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.