Skip to main content

ShotGrid Query Builder

PyPI version Python Versions Downloads Downloads/Month License: MIT Tests codecov Code style: ruff Type checked: mypy GitHub stars GitHub forks

A Pythonic query builder and ORM-like abstraction layer for ShotGrid/Flow Production Tracking API.

中文文档

🎯 Features

  • Pythonic API: Chainable query builder with intuitive method names
  • Type Safety: Full type hints and Pydantic validation
  • Flexible: Works with both shotgun_api3 and raw filter dictionaries
  • Powerful: Support for complex filters, related fields, and time-based queries
  • Lightweight: Minimal dependencies, can be used independently
  • Well-tested: Comprehensive test suite with >90% coverage

📦 Installation

# Basic installation
pip install shotgrid-query

# With ShotGrid API support
pip install shotgrid-query[shotgrid]

# For development
pip install shotgrid-query[dev]

🚀 Quick Start

Traditional ShotGrid API (Before)

import shotgun_api3

sg = shotgun_api3.Shotgun(url, script_name, api_key)

# Complex filter syntax
filters = [
    ["sg_status_list", "is", "ip"],
    ["project", "is", {"type": "Project", "id": 123}],
    ["created_at", "in_last", [7, "DAY"]]
]
fields = ["code", "description", "project.Project.name"]
result = sg.find("Shot", filters, fields)

With shotgrid-query (After)

from shotgrid_query import Query

# Chainable, readable query builder
query = (
    Query("Shot")
    .filter(sg_status_list="ip")
    .filter(project_id=123)
    .filter(created_at__in_last="7 days")
    .select("code", "description")
    .select_related("project", fields=["name"])
    .order_by("-created_at")
    .limit(100)
)

# Execute with shotgun_api3 connection
result = query.execute(sg)

# Or get raw filters/fields for manual use
filters = query.to_filters()  # Returns list of tuples
fields = query.to_fields()    # Returns list of field names

🔍 Schema Validation

Validate your queries against ShotGrid schema before execution to catch errors early:

from shotgrid_query import Query

# Development mode - auto-validate on every operation
query = Query("Shot", sg=sg, auto_validate=True)
query.filter(code="SHOT_010").select("code", "description")

# Validation happens automatically, raises ValueError if invalid
result = query.execute(sg)

Manual Validation

# Create query with schema
schema = sg.schema_field_read("Shot")
query = Query("Shot", schema=schema)
query.filter(code="SHOT_010").select("invalid_field")

# Manually validate
errors = query.validate()
if errors:
    for error in errors:
        print(f"❌ {error.field}: {error.message}")
        if error.suggestion:
            print(f"💡 {error.suggestion}")
else:
    result = query.execute(sg)

Validation on Demand

# Validate when converting to filters/fields
try:
    filters = query.to_filters(verify=True)
    fields = query.to_fields(verify=True)
except ValueError as e:
    print(f"Validation failed:\n{e}")

Detailed Error Messages

When validation fails, you get helpful error messages:

# Field doesn't exist
❌ invalid_field: Field does not exist in Shot
💡 Available fields: code, description, id, project, sg_status_list (and 45 more)

# Operator not compatible with field type
❌ code: Operator 'greater_than' is not valid for field type 'text'
💡 Valid operators for text fields: contains, ends_with, in, is, is_not, not_contains, not_in, starts_with

# Value type mismatch
❌ id: Value must be a number, got str
💡 Example: query.filter(id=123)

Schema Caching

Schema is automatically cached to avoid repeated API calls:

from shotgrid_query import SchemaCache

# Set custom TTL (default: 1 hour)
SchemaCache.set_ttl(3600)

# Clear cache if needed
SchemaCache.clear()

📚 Documentation

🤝 Contributing

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

Development Setup

  1. Clone the repository:
git clone https://github.com/loonghao/shotgrid-query.git
cd shotgrid-query
  1. Install dependencies:
pip install -e ".[dev]"
  1. Install pre-commit hooks:
pre-commit install

This will automatically run code formatting and linting checks before each commit.

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=src/shotgrid_query --cov-report=term-missing

# Run specific test file
pytest tests/test_query.py -v

Code Quality

# Format code
ruff format src tests

# Lint code
ruff check src tests

# Type check
mypy src/shotgrid_query

📄 License

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

🙏 Acknowledgments

This library was extracted from shotgrid-mcp-server to provide a reusable query builder for the ShotGrid community.

Metadata

Release files for shotgrid-query 0.3.0

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

Source distribution (sdist)

Source distribution for shotgrid-query 0.3.0
File Size Uploaded
shotgrid_query-0.3.0.tar.gz 81.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for shotgrid-query 0.3.0
File Interpreter ABI Platform
shotgrid_query-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 113.6 kB

Release files / shotgrid_query-0.3.0.tar.gz

Download URL shotgrid_query-0.3.0.tar.gz
Size 81.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b4a5e48700ee66e5c3df53879b30e115015b239c217b055456b70bec8aca980d
BLAKE2b-256 checksum
How to use checksums
56c2d754207a8e015c747280c156ae91c33c42560da93f30009d5a25614759ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2025.

Transparency log

Release files / shotgrid_query-0.3.0-py3-none-any.whl

Download URL shotgrid_query-0.3.0-py3-none-any.whl
Size 31.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a95386509d2a86cc54e0367c0ddd5f7a30ceb6c8ccd24d3caf32d42e713739ca
BLAKE2b-256 checksum
How to use checksums
ee1344bbd57f5e5ad2089fa5d850643f1c2e050fca9ef01722d44eb1233aff9d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2025.

Transparency log

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files

0.2.1

2 release files

0.2.0

2 release files

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