Skip to main content

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-string-parser.git
cd django-query-string-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-string-parser.git
cd django-query-string-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

Metadata

Release files for django-query-string-parser 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-query-string-parser 0.1.1
File Size Uploaded Provenance
django_query_string_parser-0.1.1.tar.gz 18.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-query-string-parser 0.1.1
File Interpreter ABI Platform
django_query_string_parser-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 26.3 kB

Release files / django_query_string_parser-0.1.1.tar.gz

Download URL django_query_string_parser-0.1.1.tar.gz
Size 18.7 kB
Tags Source
SHA-256 checksum
How to use checksums
74c368f9b873466b6b9571a77ad484eb762879c767f9def184efefca3c0d39d9
BLAKE2b-256 checksum
How to use checksums
6210d242596a3fe0df3948ab9a4ce0d001ad319ce6e94f0449238d59a8c0fe49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.8

Release files / django_query_string_parser-0.1.1-py3-none-any.whl

Download URL django_query_string_parser-0.1.1-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f2e2ae1e74cdef67cfb0393fe2639ddbe5e805fc47df7bb99f21aced411c0156
BLAKE2b-256 checksum
How to use checksums
85df945af603f17d8e961d9fc2ee37903c39234e21b79fbfe407cd19981ba849
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.8

Security for django-query-string-parser 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page