Skip to main content

A flexible query parser that converts query strings into Django Q objects

Project description

Django Query Parser

PyPI version Downloads Python Versions License: MIT

A flexible query parser that converts query strings into Django Q objects, enabling powerful and secure filtering in your Django applications.

Features

  • 🔍 Intuitive Query Syntax: Simple, human-readable query language
  • 🔒 Security Built-in: Whitelist allowed fields to prevent unauthorized access
  • 🎯 Django Native: Converts directly to Django Q objects
  • 🚀 Powerful Operators: Support for comparison, containment, and exclusion
  • 🔗 Logical Combinations: AND/OR logic with grouping via parentheses
  • Fast Parsing: Uses Lark parser with LALR for efficient parsing

Installation

pip install django-query-string-parser

Or install from source:

git clone https://github.com/sepehr-mohseni/django-query-parser.git
cd django-query-parser
pip install -e .

Quick Start

from django_query_parser import DjangoQueryParser
from myapp.models import Article

# Define allowed fields for security
ALLOWED_FIELDS = {'status', 'priority', 'author', 'published_date'}
parser = DjangoQueryParser(allowed_fields=ALLOWED_FIELDS)

# Parse a query string
query_string = 'status:published AND priority>=5'
q_object = parser.parse(query_string)

# Use it in a Django queryset
articles = Article.objects.filter(q_object)

Query Syntax

Basic Comparisons

Operator Meaning Example Django Lookup
: Exact match status:active status__exact
:= Exact match (alias) status:=active status__exact
~= Contains (case-insensitive) name~="John" name__icontains
!= Not equal priority!=1 ~Q(priority__exact=1)
> Greater than price>100 price__gt
< Less than price<100 price__lt
>= Greater than or equal priority>=5 priority__gte
<= Less than or equal priority<=10 priority__lte

Logical Operators

  • AND: Combine conditions (both must be true)

    status:active AND priority>=5
    
  • OR: Alternative conditions (at least one must be true)

    status:active OR status:pending
    
  • Grouping: Use parentheses to control precedence

    (status:active OR status:pending) AND priority>=5
    

Value Types

  • Strings: Quoted or unquoted

    name:"John Doe"
    status:active
    
  • Numbers: Integers or floats

    priority:5
    price:99.99
    
  • Booleans: true or false

    is_active:true
    
  • Null: null

    deleted_at:null
    

Examples

Example 1: Complex Query with Grouping

parser = DjangoQueryParser(allowed_fields={'status', 'priority', 'author'})

query = '(status:active OR status:pending) AND priority>=5 AND author~="John"'
q_object = parser.parse(query)

# Use in Django ORM
articles = Article.objects.filter(q_object)

Example 2: Exclusion and Boolean

query = 'is_published:true AND priority!=1 AND views>1000'
q_object = parser.parse(query)

articles = Article.objects.filter(q_object)

Example 3: Date Filtering (with custom field)

# Assuming you have a date field
query = 'published_date>="2024-01-01" AND published_date<"2025-01-01"'
q_object = parser.parse(query)

articles = Article.objects.filter(q_object)

Security

The parser includes built-in security features:

# Whitelist allowed fields
SAFE_FIELDS = {'status', 'priority', 'author'}
parser = DjangoQueryParser(allowed_fields=SAFE_FIELDS)

# This will raise ValueError
try:
    parser.parse('secret_data:true')
except ValueError as e:
    print(e)  # "Querying on field 'secret_data' is not allowed."

API Reference

DjangoQueryParser

__init__(allowed_fields=None)

  • allowed_fields (optional): Set of field names that are allowed to be queried. If None, all fields are allowed (not recommended for production).

parse(query_string: str) -> Q

  • query_string: The query string to parse
  • Returns: A Django Q object that can be used in .filter() or .exclude()
  • Raises: ValueError if the query is invalid or uses disallowed fields

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/sepehr-mohseni/django-query-parser.git
cd django-query-parser

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install in development mode with dev dependencies
pip install -e ".[dev]"

Running Tests

pytest

Code Formatting

black src/ tests/

Type Checking

mypy src/

Use Cases

  • API Filtering: Enable powerful filtering in REST APIs
  • Search Interfaces: Build advanced search features
  • Admin Panels: Add flexible filtering to admin interfaces
  • Data Export: Allow users to define complex export criteria

Limitations

  • Field names must be valid Python identifiers (alphanumeric and underscores)
  • No support for related field lookups (e.g., author__name) yet (coming soon)
  • Date/time values should be in ISO format strings

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

0.1.0 (2025-10-26)

  • Initial release
  • Basic query parsing with logical operators
  • Security whitelist for fields
  • Support for common comparison operators

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_query_string_parser-0.1.0.tar.gz (18.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_query_string_parser-0.1.0-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

Details for the file django_query_string_parser-0.1.0.tar.gz.

File metadata

File hashes

Hashes for django_query_string_parser-0.1.0.tar.gz
Algorithm Hash digest
SHA256 fcbea23d59506ef8ea71d351a44dc3e32207b1d03624ee4fbb59b545c562c3e6
MD5 9305da2d5a98cdec7c148fbd77e28892
BLAKE2b-256 10de9541d1eb248237c70f238a08d6f812fe456be8697955567cf9893d4366cd

See more details on using hashes here.

File details

Details for the file django_query_string_parser-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_query_string_parser-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fca899819450108eb11f6d337bfe32cc6667a3ec3b6b271ab71d84da5fdc0d74
MD5 f3e9ed6660186683c107025bd38d07c6
BLAKE2b-256 50de32a1b187e93950f1bba22400123af30faf3e861e78bb5e8fce97586facb7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page