django-solo Documentation

repository·master·Indexed 21 days ago

https://github.com/lazybird/django-solo

A tool for managing singleton models in Django, restricting database tables to a single row. It provides the SingletonModel class, a specialized SingletonModelAdmin for the admin interface, the get_solo() method for object retrieval, and a {% get_solo %} template tag. Includes support for caching via SOLO_CACHE, SOLO_CACHE_TIMEOUT, and SOLO_CACHE_PREFIX settings.

Tokens
1.4K
Snippets
6
Records
7
Agent score
26%

What's inside django-solo

  1. Install django-solo

    master

    To use Django Solo in your project, install the package via pip and add it to your Django settings.

    1. Install the package:
      pip install django-solo
    2. Add solo or solo.apps.SoloAppConfig to your INSTALLED_APPS in settings.py.
    pip install django-solo
  2. Configure Django Solo Settings

    master

    Customize the behavior of Django Solo using these settings:

    SettingDescription
    GET_SOLO_TEMPLATE_TAG_NAMEChanges the name of the template tag (default: 'get_solo')
    SOLO_ADMIN_SKIP_OBJECT_LIST_PAGEIf True, the admin will skip the object list page and go straight to the form. If False, it uses default breadcrumbs and shows the list page. (Default: True)
    SOLO_CACHEThe cache backend to use. Set to None to disable caching.
    SOLO_CACHE_TIMEOUTCache timeout in seconds.
    SOLO_CACHE_PREFIXPrefix for the cache key.
  3. Configure Caching for Singletons

    master

    By default, every call to get_solo performs a database query. You can enable caching to improve performance. When enabled, the cache is updated automatically when the object is modified via the admin.

    Use the following settings to configure caching:

    • SOLO_CACHE: The name of the cache backend to use (must be defined in your CACHES setting). Set to None to disable caching.
    • SOLO_CACHE_TIMEOUT: The cache timeout in seconds.
    • SOLO_CACHE_PREFIX: The prefix for the cache key.
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        },
        'local': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        },
    }
    
    SOLO_CACHE = 'local'
    SOLO_CACHE_TIMEOUT = 300  # 5 minutes
    SOLO_CACHE_PREFIX = 'solo'
  4. Register a Singleton Model in Admin

    master

    To get the specialized singleton admin interface (which skips the object list page and prevents adding/deleting instances), use solo.admin.SingletonModelAdmin when registering your model.

    from django.contrib import admin
    from solo.admin import SingletonModelAdmin
    from myapp.models import SiteConfiguration
    
    admin.site.register(SiteConfiguration, SingletonModelAdmin)
  5. Retrieve Singleton objects in Python

    master

    Since there is only one item in the table, you can retrieve it using standard Django ORM methods or the specialized get_solo() method.

    • Model.objects.get(): Standard retrieval.
    • Model.get_solo(): Retrieves the singleton object and creates it if it does not already exist.
    from .models import SiteConfiguration
    
    # Standard retrieval
    config = SiteConfiguration.objects.get()
    
    # Retrieves or creates the instance
    config = SiteConfiguration.get_solo()
  6. Retrieve Singleton objects in Django Templates

    master

    You can access singleton objects directly in templates using the {% get_solo %} tag. You must load the solo_tags library first.

    Important: When extending a template, ensure the tag is used within the correct scope (e.g., inside a {% block %}).

    {% load solo_tags %}
    {% get_solo 'app_label.ModelName' as my_config %}
    {{ my_config.field_name }}
    
    {# Example in an extended template #}
    {% extends "index.html" %}
    {% load solo_tags %}
    
    {% block content %}
        {% get_solo 'config.SiteConfiguration' as site_config %}
        {{ site_config.site_name }}
    {% endblock content %}
  7. Define a Singleton Model

    master

    To create a model that only allows one instance, inherit from solo.models.SingletonModel.

    Note: You do not need to provide verbose_name_plural in the Meta class; Django Solo uses the verbose_name instead.

    If you are converting an existing model with data to a singleton, you can specify which row to use as the singleton by setting the singleton_instance_id property.

    from django.db import models
    from solo.models import SingletonModel
    
    class SiteConfiguration(SingletonModel):
        site_name = models.CharField(max_length=255, default='Site Name')
        maintenance_mode = models.BooleanField(default=False)
    
        def __str__(self):
            return "Site Configuration"
    
        class Meta:
            verbose_name = "Site Configuration"
    
    # To migrate an existing model with a specific ID:
    class SiteConfiguration(SingletonModel):
        singleton_instance_id = 24
        # (...)