DISQUS

David Cramer's Blog: Singletons in Django

  • tcdavis · 1 year ago
    So, two questions.

    1. Per your explanation, it wasn't strictly necessary to define Article as a SingleModel, correct?

    2. Given the obvious benefits, are there any reasons not to use this class for all models? Am I missing something crucial here?
  • David Cramer · 1 year ago
    Personally, I plan to use it throughout the codebase to prevent some data issues. The one area this doesn't affect right now (due to complications we had with it at Curse) is serialization. It will ignore the instance caching when you unserialize objects (such as from the cache).
  • Rob Hudson · 1 year ago
    Could there be a way to enable this per query? In your example, it's obvious that creating only one instance per category is optimal, but are there cases where it may not be what you want?
  • David Cramer · 1 year ago
    I think per query is a bit out of scope for what I want to achieve. Doing this would require the queryset/manager to be aware (to some extent) of the singleton model. This wouldn't quite achieve the same performance benefit.

    The biggest thing about this, while it IS an obvious performance boost, its not the sole intention of the project. Having unique instances of an object in memory can solve a lot of other issues as well.
  • Sam Toriel · 1 year ago
    ^^ My questions exactly
  • Steingrim · 1 year ago
    I think calling this Singletons is quite misleading. The Singleton Pattern is used to enforce a single instance of a class; not a single instance of a business entity. Identity Map is the correct naming but note Fowler's emphasis on using one Identity Map per transaction.
  • David Cramer · 1 year ago
    Ah if you are correct then I will be renaming the project. I haven't done much research (in terminology), but had assumed it was correct via the ticket on Django.
  • dailycad · 1 year ago
    Very useful info.. Thanks..
  • Tom. · 1 year ago
    This sounds wicked! Thanks.