Limit number of model instances to be created - django

前端 未结 6 1521
萌比男神i
萌比男神i 2020-12-02 20:36

I have model from which I only want to create one instance, and no more instances should be allowed.

Is this possible? I\'ve got a feeling that I\'ve seen this done

6条回答
  •  自闭症患者
    2020-12-02 21:17

    @ncoghlan your solution is working fine, but not very user-friendly: the user has access to the creation form and will think he/she can use it, even though he/she will never be able to save it.

    It's actually possible to combine it with Brendan's solution, which will hide the 'Add' button. Using Mixins for easy reuse:

    # models.py
    from django.db import models
    from django.core.exceptions import ValidationError
    
    class SingleInstanceMixin(object):
        """Makes sure that no more than one instance of a given model is created."""
    
        def clean(self):
            model = self.__class__
            if (model.objects.count() > 0 and self.id != model.objects.get().id):
                raise ValidationError("Can only create 1 %s instance" % model.__name__)
            super(SingleInstanceMixin, self).clean()
    
    class Example(SingleInstanceMixin, models.Model):
        pass
    
    
    # admin.py
    from django.contrib import admin
    from example.models import Example
    
    class SingleInstanceAdminMixin(object):
        """Hides the "Add" button when there is already an instance."""
        def has_add_permission(self, request):
            num_objects = self.model.objects.count()
            if num_objects >= 1:
                return False
            return super(SingleInstanceAdminMixin, self).has_add_permission(request)
    
    class ExampleAdmin(SingleInstanceAdminMixin, admin.ModelAdmin):
         model = Example
    

提交回复
热议问题