Models are typically defined in the
models.py 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.
titleis a text with a maximum length of 100 characters
ForeignKeywhich represents a relationship to another model/table, in this case
Author(used only for example purposes).
on_deletetells 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_deletecan 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
publish_datestores a date. Both
blankare set to
Trueto 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.