Limit single entry in model for django application?

I want to use a model to save system settings for a django application. So I want to limit the model to just one entry, how do I make a limit?

+3
source share
5 answers

A simple way is to use the parameter name as the primary key in the settings table. There cannot be more than one record with the same primary key, so this will allow Django and the database to guarantee integrity.

+3
source

Try the following:

class MyModel(models.Model):
    onefield = models.CharField('The field', max_length=100)

class MyModelAdmin(admin.ModelAdmin):
  def has_add_permission(self, request):
    # if there already an entry, do not allow adding
    count = MyModel.objects.all().count()
    if count == 0:
      return True

    return False
+5
source

has_add_permission , Django ( ). , :

class SettingAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        base_add_permission = super(SettingAdmin, self).has_add_permission(request)
        if base_add_permission:
            # if there already an entry, do not allow adding
            count = Setting.objects.all().count()
            if count == 0:
                return True
        return False
+5

, , .

def has_add_permission(self, *args, **kwargs):
    return not MyModel.objects.exists()

Django:

. , , , , . ().

https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated

+3

Source: https://habr.com/ru/post/1729333/


All Articles