Introduction
Django web applications interact with data through Python objects known as models. These models dictate the organization of stored data, specifying field types, maximum sizes, default values, selection options, documentation help text, form label text, and more. Importantly, the definition of a model remains independent of the underlying database, offering flexibility to choose from various options within project settings. Once a database is selected, direct communication with it becomes unnecessary. Instead, developers focus on defining the model structure and additional code, leaving Django to handle the intricate database interactions.
Designing the LocalLibrary models
Before delving into coding the LocalLibrary models, it's crucial to consider the data needed and the relationships between entities. We must store book details like title, summary, author, language, category, and ISBN, along with managing multiple available copies and potentially complex author information. Using separate models for distinct "objects" such as books, book instances, and authors is advisable. Employing models for selection-list options, like genres and languages, offers flexibility as options may evolve. Django's relationship options allow for defining connections like one-to-one, one-to-many, and many-to-many. The UML diagram provided outlines the models to be defined, along with their relationships and multiplicities. Models for books, book instances, authors, and genres are established, with certain values like book instance status being hardcoded for simplicity. This UML diagram serves as a guide for designing the LocalLibrary models effectively.
Defining the LocalLibrary Models
In this section, we will start defining the models for the library. Open models.py (in /django-locallibrary-tutorial/catalog/). The boilerplate at the top of the page imports the model module, which contains the model base class models. The model that our models will inherit from.
from django.db import models
# Create your models here.
Model for Book Genres
Add the following code snippet to the end of your models.py file to implement the Genre model. This model serves the purpose of storing information about various book categories, such as fiction, non-fiction, romance, military history, and more. Unlike using free text or a selection list, we've designed this model to ensure that the possible genre values can be effectively managed through the database rather than being hardcoded.
from django.urls import reverse # Utilized in get_absolute_url() to retrieve URL for a specified ID
from django.db import models
from django.db.models import UniqueConstraint # Enforces fields to contain unique values
from django.db.models.functions import Lower # Produces a lower-cased value of a field
class Genre(models.Model):
"""Model representing different book genres."""
name = models.CharField(
max_length=200,
unique=True,
help_text="Enter a book genre (e.g. Science Fiction, French Poetry, etc.)"
)
def __str__(self):
"""String representation of the Model object."""
return self.name
def get_absolute_url(self):
"""Returns the URL to access a particular genre instance."""
return reverse('genre-detail', args=[str(self.id)])
class Meta:
constraints = [
UniqueConstraint(
Lower('name'),
name='genre_name_case_insensitive_unique',
violation_error_message="Genre already exists (case insensitive match)"
),
]
Explanation
The model consists of a single CharField named 'name', which describes the genre. This field is limited to 200 characters and includes helpful text for guidance.
The 'name' field is set to unique (unique=True) to ensure there's only one record for each genre.
Following the field declaration, there's a str() method defined, which returns the name of the genre for a particular record.
Additionally, a get_absolute_url() method is defined to generate a URL that provides access to a detailed record of this model. For this method to work correctly, a URL mapping with the name 'genre-detail' needs to be defined, along with an associated view and template.
By setting unique=True on the 'name' field, we prevent the creation of genres with identical names. However, variations such as "fantasy", "Fantasy", or "FaNtAsY" are not prevented. To address this, the last part of the model definition utilizes constraints within the model's metadata. It specifies that the lowercase of the value in the 'name' field must be unique in the database. If a duplicate is encountered, the specified violation_error_message is displayed. Multiple constraints can be defined for a field or fields, offering flexibility in data validation and management. Refer to the Constraints reference, including UniqueConstraint() and Lower(), for further information.
Book Model
class Book(models.Model):
"""Model representing a book (but not a specific copy of a book)."""
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.RESTRICT, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books.
# Author as a string rather than object because it hasn't been declared yet in file.
summary = models.TextField(
max_length=1000, help_text="Enter a brief description of the book")
isbn = models.CharField('ISBN', max_length=13,
unique=True,
help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn'
'">ISBN number</a>')
# ManyToManyField used because genre can contain many books. Books can cover many genres.
# Genre class has already been defined so we can specify the object above.
genre = models.ManyToManyField(
Genre, help_text="Select a genre for this book")
def __str__(self):
"""String for representing the Model object."""
return self.title
def get_absolute_url(self):
"""Returns the URL to access a detail record for this book."""
return reverse('book-detail', args=[str(self.id)])
Explanation
- The Book model comprises fields for the title, author, summary, ISBN, and genre.
- 'title' stores the title of the book.
- 'author' is a ForeignKey, linking each book to a specific author. This allows authors to have multiple books.
- 'summary' is a TextField, accommodating longer descriptions of the book.
- 'isbn' represents the ISBN number of the book. It's set to unique to ensure each book has a globally unique ISBN.
- 'genre' is a ManyToManyField, allowing a book to belong to multiple genres and vice versa.
- In the 'author' field, 'Author' is referred to as a string due to its declaration occurring later in the file.
- The 'str()' method returns the title of the book for better readability.
- The 'get_absolute_url()' method generates a URL to access detailed information about a specific book instance.
- It's noted that 'on_delete=models.RESTRICT' is used for the 'author' field to prevent the deletion of associated authors if referenced by any book. This differs from the default behavior 'on_delete=models.CASCADE', which would delete the book if its author is deleted. Other options such as 'PROTECT' and 'SET_NULL' are mentioned for handling author deletions.
BookInstance Model
Now, let's introduce the BookInstance model, which should be placed among your other models. This model signifies a particular copy of a book that patrons might borrow from the library. It encompasses details such as the availability status, expected return date, imprint (specific version) details, and a unique identifier for the book within the library.
Some elements of this model will seem familiar, as it utilizes:
- ForeignKey to establish the association with the corresponding Book (each book may have multiple copies, but a copy is tied to only one Book). The 'on_delete=models.RESTRICT' setting ensures that a Book cannot be deleted while any BookInstance references it.
- CharField to represent the imprint or specific version of the book.
import uuid # Required for unique book instances
class BookInstance(models.Model):
"""Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4,
help_text="Unique ID for this particular book across whole library")
book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True)
imprint = models.CharField(max_length=200)
due_back = models.DateField(null=True, blank=True)
LOAN_STATUS = (
('m', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(
max_length=1,
choices=LOAN_STATUS,
blank=True,
default='m',
help_text='Book availability',
)
class Meta:
ordering = ['due_back']
def __str__(self):
"""String for representing the Model object."""
return f'{self.id} ({self.book.title})'





Join the conversation! Your thoughts help the community grow.