Django Creating your first model


Models are typically defined in the file under your application subdirectory. The Model class of django.db.models module is a good starting class to extend your models from. For example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='authored_books')
    publish_date = models.DateField(null=True, blank=True)

    def __str__(self): # __unicode__ in python 2.*
        return self.title

Each attribute in a model represents a column in the database.

  • title is a text with a maximum length of 100 characters
  • author is a ForeignKey which represents a relationship to another model/table, in this case Author (used only for example purposes). on_delete tells the database what to do with the object should the related object (an Author) be deleted. (It should be noted that since django 1.9 on_delete can be used as the second positional argument. In django 2 it is a required argument and it is advisable to treat it as such immediately. In older versions it will default to CASCADE.)
  • publish_date stores a date. Both null and blank are set to True to indicate that it is not a required field (i.e. you may add it at a later date or leave it empty.)

Along with the attributes we define a method __str__ this returns the title of the book which will be used as its string representation where necessary, rather than the default.