Skip to main content

A powerful Django query string parser that converts URL query parameters into Django ORM filters

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-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

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.1.tar.gz (18.7 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.1-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for django_query_string_parser-0.1.1.tar.gz
Algorithm Hash digest
SHA256 74c368f9b873466b6b9571a77ad484eb762879c767f9def184efefca3c0d39d9
MD5 0fb543ab07bde9564f09d1d3775e4ced
BLAKE2b-256 6210d242596a3fe0df3948ab9a4ce0d001ad319ce6e94f0449238d59a8c0fe49

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_query_string_parser-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f2e2ae1e74cdef67cfb0393fe2639ddbe5e805fc47df7bb99f21aced411c0156
MD5 8145dcf8d29937344f851b994f78d6e3
BLAKE2b-256 85df945af603f17d8e961d9fc2ee37903c39234e21b79fbfe407cd19981ba849

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