Limit number of model instances to be created - django

Viewed 12722

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 somewhere, but unfortunately I'm unable to locate it.

EDIT: I need this for a stupidly simple CMS. I have an abstract class for which FrontPage and Page classes inherits. I only want to be able to create one frontpage object.

The difference between the FrontPage object and the Page objects are that they're supposed to have slightly different fields and templates, and as mentioned only one FrontPage is to be created.

6 Answers

You can do something like this, from the Django docs:

class ModelWithOnlyOneInstance(models.Model):
    ... fields ...

    def save(self, *args, **kwargs):
      if ModelWithOnlyOneInstance.objects.count() > 1:
        return

      super(ModelWithOnlyOneInstance, self).save(*args, **kwargs)

If you only want one instance of a model , perhaps 'there is an app for that!'

You can check django-solo witch is a complete solution for what you need.

here is a link -> https://github.com/lazybird/django-solo

It comes with a class for singleton models and one for admin singleton models, witch does not add an s to the end of the model name, exclude the intermediary screen witch lists all objects and also removes the 'add' button and the 'save and add another' button.

It also comes with some other fluffy and useful stuff like importing the singletons directly on your templates, etc...

I would override create() method on default manager, but as stated above, this won't guarantee anything in multi-threaded environment.

Related