Django Sequences

3.0 · active · verified Thu Apr 16

django-sequences is a Python library for Django that provides a reliable way to generate gapless sequences of integer values. Unlike Django's default auto-incrementing primary keys, which can have gaps due to rolled-back transactions, this library ensures sequential integrity. It is currently at version 3.0, actively maintained, and compatible with modern Django versions (3.2 and up).

Common errors

Warnings

Install

Imports

Quickstart

To generate a gapless sequence, ensure that `get_next_value()` and the subsequent database save operation occur within the same atomic transaction. The library provides `get_next_value()` for a functional approach and a `Sequence` class for an object-oriented API. Remember to add `sequences.apps.SequencesConfig` to your `INSTALLED_APPS` and run migrations.

import os
from django.db import transaction
from sequences import get_next_value

# Assume 'Invoice' is a Django model with an 'number' field
# from invoices.models import Invoice

# For demonstration, we'll mock a model and save operation
class MockInvoice:
    _instances = []
    def __init__(self, number):
        self.number = number
        print(f"Created MockInvoice with number: {self.number}")
        MockInvoice._instances.append(self)

def create_invoice_with_sequence(sequence_name='invoice_numbers'):
    try:
        with transaction.atomic():
            next_invoice_number = get_next_value(sequence_name)
            # Replace with your actual model creation:
            # Invoice.objects.create(number=next_invoice_number)
            MockInvoice(number=next_invoice_number)
            print(f"Successfully committed invoice with number: {next_invoice_number}")
    except Exception as e:
        print(f"Transaction failed: {e}")

# Example usage:
create_invoice_with_sequence('orders')
create_invoice_with_sequence('orders')
create_invoice_with_sequence('shipments', initial_value=1000)
create_invoice_with_sequence('shipments')

view raw JSON →