bhylu.com

Advertisements

Django Q Objects

Q objects describe conditions that can be combined with OR, AND and negation. Parentheses make the intended grouping visible.

How it works

Use ordinary keyword arguments for a simple conjunction. Reach for Q when a condition includes alternatives such as a low seat count or a title match. Keep the public visibility filter outside the alternative when it must apply to every branch. Otherwise an OR can accidentally expose drafts. This is a logic problem even though the ORM still parameterizes values safely.

Run in the supplied local Django project

This lesson uses Django 5.2.18 LTS with Python 3.12. Download the source downloader and run node download-project.mjs http://127.0.0.1:8000 with Node 22 while previewing locally. It creates a new bhylu-django-lab folder and refuses to overwrite an existing one. After deployment, the default base is bhylu.com; until then use your local preview URL.

Inside that new folder, create a virtual environment, install requirements.txt and run the complete lesson file shown below. Every lesson creates a fresh in-memory SQLite database and temporary upload storage. It does not edit the interactive lab’s db.sqlite3 or Bhylu’s database. The visible listing below is the lesson’s core code; its complete downloaded file includes the shared bootstrap.

Django does not run in Bhylu’s current browser playground. No Apache, MySQL or global PHP configuration change is needed. See the setup lesson for the full project and commands.

Example

Run .venv\Scripts\python.exe lessons\q-expressions.py from the downloaded project root. Download the complete lesson file; keep it under lessons/. The project’s shared models, forms, views and fixture are prerequisites, not a hidden online runtime.

lessons/q-expressions.py — core code

from django.db.models import Q
rows = Workshop.objects.filter(published=True).filter(Q(remaining__lt=5) | Q(title__startswith="Lamp"))
print(list(rows.values_list("slug", flat=True)))
print(Workshop.objects.filter(~Q(published=True)).count())

Expected result

['lamp-care', 'bike-punctures']
1

Both public workshops satisfy one alternative, while one separate draft matches the negated published condition. The explicit outer visibility filter prevents an unrelated low-seat draft from entering the public result.

Use Django’s versioned official documentation for exact API contracts and the deployment checklist before a separate release.

Advertisements