Allow only one instance of a model in Django

后端 未结 7 1106
南笙
南笙 2020-12-06 00:57

I would like to control some configuration settings for my project using a database model. For example:

class JuicerBaseSettings(models.Model):
    max_rpm =         


        
相关标签:
7条回答
  • 2020-12-06 01:39

    Either you can override save and create a class function JuicerBaseSettings.object()

    class JuicerBaseSettings(models.Model):
    
        @classmethod
        def object(cls):
            return cls._default_manager.all().first() # Since only one item
    
        def save(self, *args, **kwargs):
            self.id = 1
            return super().save(*args, **kwargs)
    

    ============= OR =============

    Simply, Use django_solo.

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

    Snippet Courtsy: django-solo-documentation.

    # models.py
    
    
    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 __unicode__(self):
            return u"Site Configuration"
    
        class Meta:
            verbose_name = "Site Configuration"
    
    # admin.py
    
    from django.contrib import admin
    from solo.admin import SingletonModelAdmin
    from config.models import SiteConfiguration
    
    admin.site.register(SiteConfiguration, SingletonModelAdmin)
    
    # There is only one item in the table, you can get it this way:
    from .models import SiteConfiguration
    config = SiteConfiguration.objects.get()
    
    # get_solo will create the item if it does not already exist
    config = SiteConfiguration.get_solo()
    
    0 讨论(0)
提交回复
热议问题