Ticket #17436: patch_17436.diff

File patch_17436.diff, 1.6 KB (added by Zbigniew Siciarz, 13 years ago)

Note about overriding init and other approaches to customize instance creation.

  • docs/ref/models/instances.txt

    diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt
    index d84fb3e..120f9a4 100644
    a b The keyword arguments are simply the names of the fields you've defined on your  
    2525model. Note that instantiating a model in no way touches your database; for
    2626that, you need to :meth:`~Model.save()`.
    2727
     28.. note::
     29    You may be tempted to customize the model and override the ``__init__``
     30    method. However, take care not to change the calling signature, as any
     31    change may prevent the model instance from being saved. Try using one of
     32    alternative approaches instead. First of these involves a classmethod on
     33    the model class::
     34
     35        class Book(models.Model):
     36            title = models.CharField(max_length=100)
     37
     38            @classmethod
     39            def create(cls, title):
     40                book = cls(title=title)
     41                # do something with the book
     42                return book
     43
     44    You can then use the method as follows::
     45
     46        book = Book.create("Pride and Prejudice")
     47
     48    Another (and usually preferred) way is to define a method on a custom
     49    manager::
     50
     51        class BookManager(models.Manager):
     52            def create_book(title):
     53                book = self.create(title=title)
     54                # do something with the book
     55                return book
     56
     57        class Book(models.Model):
     58            title = models.CharField(max_length=100)
     59
     60            objects = BookManager()
     61
     62    And use it like this::
     63
     64        book = Book.objects.create_book("Pride and Prejudice")
     65
    2866.. _validating-objects:
    2967
    3068Validating objects
Back to Top