db.models.Model

class Model(**kwargs) [source]

The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().

Note

You may be tempted to customize the model by overriding the __init__ method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding __init__, try using one of these approaches:

  1. Add a classmethod on the model class:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    from django.db import models
     
    class Book(models.Model):
        title = models.CharField(max_length=100)
     
        @classmethod
        def create(cls, title):
            book = cls(title=title)
            # do something with the book
            return book
     
    book = Book.create("Pride and Prejudice")
  2. Add a method on a custom manager (usually preferred):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class BookManager(models.Manager):
        def create_book(self, title):
            book = self.create(title=title)
            # do something with the book
            return book
     
    class Book(models.Model):
        title = models.CharField(max_length=100)
     
        objects = BookManager()
     
    book = Book.objects.create_book("Pride and Prejudice")
doc_Django
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.