Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #17436 - Added warning about overriding Model.__init__()

Thanks zsiciarz for the draft patch.
  • Loading branch information...
commit 7313468f85c3ade1275fc7fef193a4429f4af4bf 1 parent e747873
authored July 01, 2012

Showing 1 changed file with 35 additions and 1 deletion. Show diff stats Hide diff stats

  1. 36  docs/ref/models/instances.txt
36  docs/ref/models/instances.txt
@@ -25,6 +25,41 @@ The keyword arguments are simply the names of the fields you've defined on your
25 25
 model. Note that instantiating a model in no way touches your database; for
26 26
 that, you need to :meth:`~Model.save()`.
27 27
 
  28
+.. note::
  29
+
  30
+    You may be tempted to customize the model by overriding the ``__init__``
  31
+    method. If you do so, however, take care not to change the calling
  32
+    signature as any change may prevent the model instance from being saved.
  33
+    Rather than overriding ``__init__``, try using one of these approaches:
  34
+
  35
+    1. Add a classmethod on the model class::
  36
+
  37
+        class Book(models.Model):
  38
+            title = models.CharField(max_length=100)
  39
+
  40
+            @classmethod
  41
+            def create(cls, title):
  42
+                book = cls(title=title)
  43
+                # do something with the book
  44
+                return book
  45
+
  46
+        book = Book.create("Pride and Prejudice")
  47
+
  48
+    2. Add a method on a custom manager (usually preferred)::
  49
+
  50
+        class BookManager(models.Manager):
  51
+            def create_book(title):
  52
+                book = self.create(title=title)
  53
+                # do something with the book
  54
+                return book
  55
+
  56
+        class Book(models.Model):
  57
+            title = models.CharField(max_length=100)
  58
+
  59
+            objects = BookManager()
  60
+
  61
+        book = Book.objects.create_book("Pride and Prejudice")
  62
+
28 63
 .. _validating-objects:
29 64
 
30 65
 Validating objects
@@ -604,4 +639,3 @@ described in :ref:`Field lookups <field-lookups>`.
604 639
 Note that in the case of identical date values, these methods will use the
605 640
 primary key as a tie-breaker. This guarantees that no records are skipped or
606 641
 duplicated. That also means you cannot use those methods on unsaved objects.
607  
-

0 notes on commit 7313468

Please sign in to comment.
Something went wrong with that request. Please try again.