views:

107

answers:

2

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.

+1  A: 

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)
Dominic Rodger
This doesn't guarantee that at most one instance will be created - unless there is only one thread/process.
Tomasz Zielinski
That's true - if you're really that worried about it, I think you'll need to do something with the `post_save` signal, and start playing with thread synchronisation.
Dominic Rodger
A: 

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

Dmitry Shevchenko