django-postgres-extra

2.0.9 · active · verified Tue Apr 14

django-postgres-extra brings advanced PostgreSQL features like HStore fields, partitioned models, and enhanced querying capabilities directly into Django's ORM. It seamlessly integrates with Django models and querysets, allowing developers to leverage PostgreSQL-specific functionality without writing raw SQL. The current stable version is 2.0.9, with a 3.0.0 release candidate recently published, indicating an active development and release cadence.

Warnings

Install

Imports

Quickstart

To use `django-postgres-extra`, you must add 'pg_extra' to your `INSTALLED_APPS` in `settings.py`. This example demonstrates defining a model with an `HStoreField`, allowing flexible key-value storage. After adding the app and defining the model, run `python manage.py makemigrations` and `python manage.py migrate`.

import os
from django.conf import settings
from django.db import models

# Minimal Django setup (for demonstration only)
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=['pg_extra', __name__],
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.postgresql',
                'NAME': os.environ.get('PG_DB_NAME', 'test_db'),
                'USER': os.environ.get('PG_DB_USER', 'user'),
                'PASSWORD': os.environ.get('PG_DB_PASSWORD', 'password'),
                'HOST': os.environ.get('PG_DB_HOST', 'localhost'),
                'PORT': os.environ.get('PG_DB_PORT', '5432')
            }
        },
        DEFAULT_AUTO_FIELD='django.db.models.BigAutoField'
    )

from pg_extra.fields import HStoreField

class Product(models.Model):
    name = models.CharField(max_length=255)
    properties = HStoreField(blank=True, null=True, default=dict)

    def __str__(self):
        return self.name

    class Meta:
        app_label = 'my_app' # Required for this minimal setup

# Example usage (requires a configured Django project and migrations applied)
# print('Ensure pg_extra is in INSTALLED_APPS and run migrations.')
# try:
#     p = Product.objects.create(name='Smartphone', properties={'color': 'black', 'storage_gb': '128'})
#     print(f"Created product: {p.name} with properties {p.properties}")
#     retrieved_p = Product.objects.get(name='Smartphone')
#     print(f"Retrieved product color: {retrieved_p.properties['color']}")
# except Exception as e:
#     print(f"Error during quickstart: {e}")

view raw JSON →