| 1 | |
| 2 | = Single Instance = |
| 3 | |
| 4 | This page describes the issues and proposals pertaining to the fact that django's ORM will create as many instances of the same DB object as there are request. |
| 5 | |
| 6 | |
| 7 | == Issues == |
| 8 | * #5514 describes what I think is the main issue with the current behavior of the ORM. Having multiple instances can result in silent data losses. Even worse the actual result would depend on whether one used select_related or not. |
| 9 | * The original goal of #17 was reducing memory use by reusing the same instance instead of having a new one. |
| 10 | |
| 11 | == Proposals == |
| 12 | The basic idea of #17 is to simply reuse existing instances. This works by keeping track of instanciated objects on a per model basis. Whenever we try to instanciate a model, we check if there is already an instance in memory and reuse it if so. This would solve both issues mentionned above. Please note that the proposal is absolutely NOT a caching system. Whenever an instance goes out of scope it is still discarded. |
| 13 | |
| 14 | To understand the benefits of the proposed patch, let's see a small example: |
| 15 | {{{ |
| 16 | class ArticleType(models.Model): |
| 17 | name = models.CharField(maxlength=200) |
| 18 | categories = models.CharField(maxlength=200) |
| 19 | |
| 20 | class Article(models.Model): |
| 21 | title = models.CharField(maxlength=200) |
| 22 | type_of_article = models.ForeignKey(ArticleType) |
| 23 | |
| 24 | for article in Article.objects.all(): |
| 25 | print "%s (%s)" % (article.title, article.type_of_article.name) |
| 26 | }}} |
| 27 | If you have a great number of Articles and a smaller number of ArticleTypes the perfomance/memory hit is staggering: |
| 28 | * you do a request per Article to get the type |
| 29 | * you have as many ArticleType instances in memory as there are articles |
| 30 | |
| 31 | == Implementation == |
| 32 | #17 currently has a working patch doing the following: |
| 33 | * |
| 34 | |
| 35 | |
| 36 | but some things are missing: |
| 37 | * more detailled docs |
| 38 | * API cleanup |
| 39 | |
| 40 | |
| 41 | |
| 42 | === Threads === |
| 43 | The current #17 patch does not handle threads but the design calls for per-thread instance uniqueness only. No sharing would occur between threads, as is the case currently. |
| 44 | |
| 45 | |