Skip to main content

django-dbchoices

⚡ Simple Runtime Choices for Django Models & Forms

django-dbchoices provides a clean, lightweight way to manage dynamic choices in Django; backed by the database. It’s built for cases where valid choices depend on context—such as tenancy, environment, or configuration—and where hard-coded enums or frequent migrations become a bottleneck.

Key Features

  • Plug-and-play integration: Works seamlessly with Django Models, Forms, Admin, DRF, and more.
  • Runtime Evaluation: Choices are resolved dynamically when models and forms are loaded.
  • Code-defined defaults: Declare default choices in code and easily sync them to the database.
  • Built-in caching: Reduces database hits and keeps performance snappy.
  • Swappable by design: Bring your own model to support multi-tenancy or attach extra metadata.

📦 Installation & Setup

pip install django-dbchoices

Add to your settings.py:

# settings.py
INSTALLED_APPS = [
    # ...
    'dbchoices',
]

Workflow

  1. Migrate: Apply the package's initial migrations.

    python manage.py migrate
    
  2. Define Defaults: Register your required choices in your application's AppConfig.ready() method:

    class MyAppConfig(AppConfig):
        name = 'myapp'
    
        def ready(self) -> None:
            from dbchoices.registry import ChoiceRegistry
    
            # Register choices using tuples
            ChoiceRegistry.register_defaults("Status", [
                ("PENDING", "Booking Pending"),
                ("COMPLETE", "Booking Complete"),
                ("FAILED", "Booking Failed"),
            ])
    
            # Or using TextChoices and/or Enums
            ChoiceRegistry.register_enum(StatusEnum)
    
  3. Synchronize: Run the management command to push your code definitions into the database.

    python manage.py dbchoices --sync
    

And you're all set! Your choices are now ready for use in models and forms.


Usage

Defining Models

Use the custom DynamicChoiceField to define the choice field(s) in the models. This field handles the necessary hooks for validation and display.

# myapp/models.py
from dbchoices.fields import DynamicChoiceField

class Ticket(models.Model):
    status = DynamicChoiceField(group_key='Status', default='PENDING')

Alternatively, if you wish to keep using standard Django fields, you can use DynamicChoiceValidator.

Note: This approach does not support automatic label/choice rendering in Django Admin/Forms.

# myapp/models.py
from django.db import models
from dbchoices.registry import ChoiceRegistry

class Ticket(models.Model):
    status = models.CharField(
        default='PENDING',
        validators=[DynamicChoiceValidator(group_key='Status')],
    )

API Access

The registry also provides helper methods for obtaining human-readable labels and models.TextChoices in your code logic.

Note: It is discouraged to use get_enum in typing-critical paths due to the ephemeral nature of runtime choices.

from dbchoices.registry import ChoiceRegistry

# Get the readable label
readable_status = ChoiceRegistry.get_label('ticket_status', 'in_progress')

# Get the Enum class for code logic
Status = ChoiceRegistry.get_enum('ticket_status')
if ticket.status == Status.CLOSED:
    # ...

Settings

You can customize the behavior of django-dbchoices using the following settings in your settings.py:

# settings.py
# Cache timeout for dynamic choices (default: 1 hour)
DBCHOICES_CACHE_TIMEOUT = 3600

# Cache alias to use for caching dynamic choices (default: 'default')
DBCHOICES_CACHE_ALIAS = 'default'

# Whether to auto-invalidate cache on choice updates (default: True)
DBCHOICES_AUTO_INVALIDATE_CACHE = True

# Custom choice model path (default: 'dbchoices.Choice')
DBCHOICE_MODEL = 'myapp.CustomChoiceModel'

License

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

Metadata

Release files for django-dbchoices 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-dbchoices 0.1.1
File Size Uploaded
django_dbchoices-0.1.1.tar.gz 10.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-dbchoices 0.1.1
File Interpreter ABI Platform
django_dbchoices-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 26.4 kB

Release files / django_dbchoices-0.1.1.tar.gz

Download URL django_dbchoices-0.1.1.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1b15458ee6065776c2334636240723d832a6942d2bdbb298cc4cecb43a283ae6
BLAKE2b-256 checksum
How to use checksums
3126a76215332d0fdb15c60f8530a5c542eb55087bacc41ffc182adbbe1c2a84
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

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

Download URL django_dbchoices-0.1.1-py3-none-any.whl
Size 15.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a335dd39d975bf7826c7cae6d4ba7c1db877dc6102dfeb527e039ae894b0b2d1
BLAKE2b-256 checksum
How to use checksums
fa736df0d9a5a3e92f8690b89bed0b1133ca21e5f96d20a94c86431323bb8d7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

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