Code 401 Class 27 Reading Notes
Using Models
- Django web applications access and manage data through Python objects referred to as models.
- When designing your models have separate models for every “object”(a group of related information)
- Have the models represent selection-list options, like a drop down list of choices.
- Once models and fields are decided, think about the relationships
- models.py file define an applications models. They can include fields, methods and metadata.
- Fields, data types that are determined by arbitrary number of fields which can represent a column of data what can be stored in database tables.
Common Field Arguments
- help_text: Provides a text label for HTML forms (e.g in the admin), as described above.
- verbose_name: A human-readable name for the field used in field labels. If not specified, Django will infer the default verbose name from the field name.
- default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created.
- null: If
True
, Django will store blank values asNULL
in the database for fields where this is approprioate (aCharField
will instead store an empty string). The default isFalse
. - blank: If
True
, the field is allowed to be blank in your forms. The default isFalse
, which means that Django’s form validation will force you to enter a value. This is often used withnull=True
, because if you’re going to allow blank values, you also want the database to be able to represent them appropriately. - choices: A group of choices for this field. If this is provided, the default corresponding form widget will be a slect box with these choices instead of the standard text field.
- primary_key: If
True
, sets the current field as the primary key for the model (A primary key is a special database column designated to uniquely identify all the different table records). If no field is specified as the primary key then Django will automatically add afield for this purpose.The typ of auto-created primary key fields can be specified for each app in[AppConfig.default_auto_field](https://docs.djangoproject.com/en/4.0/ref/applications/#django.apps.AppConfig.default_auto_field)
or globally in the[DEFAULT_AUTO_FIELD](https://docs.djangoproject.com/en/4.0/ref/settings/#std:setting-DEFAULT_AUTO_FIELD)
setting.
Common Field Types
There are many types of fields, including fields for different types of numbers (big integers, small integers, floats, floats), booleans, URLs, slugs, unique ids, and other “time-related” information (durations, time,etc.). Full list here.
- class Meta; declars model-level metadata for Model by declaring.
class Meta:
ordering = ['-my_field_name']
- Models can have methods.
def __str__(self):
return self.field_name
Model Management
Use model classes to create, update, or delete records, and to run queries to get all records or particular subsets of records.
Creating and modifying records
# Create a new record using the model's constructor.
record = MyModelName(my_field_name="Instance #1")
# Save the object into the database.
record.save()
Call save()
to store modified values to the database.
Genre model
The code below is used to store information about the book category - for example whether it is fiction or non-fiction, romance or military history, etc.
class Genre(models.Model):
"""Model representing a book genre."""
name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')
def __str__(self):
"""String for representing the Model object."""
return self.name
Book Model
The code below represents all information about an available book in a general sense, but not a particular physical “instance” or “copy” available for loan.
from django.urls import reverse # Used to generate URLs by reversing the URL patterns
class Book(models.Model):
"""Model representing a book (but not a specific copy of a book)."""
title = models.CharField(max_length=200)
# 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 the file
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
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)])
BookInstance Model
The code below represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, “imprint” or version details, and a unique id for the book in the library.
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})'
Re-run the database migrations
All the models have now been created. Now re-run your database migrations to add them to your database.
python3 manage.py makemigrations
python3 manage.py migrate
Django Admin
The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.
After registering the models we’ll show how to create a new “superuser”, login to the site, and create some books, authors, book instances, and genres.
Registering models
Open and register models in admin.py. The below code will import the models and calls admin.site.register
to register each of them.
from django.contrib import admin
# Register your models here.
from .models import Author, Genre, Book, BookInstance
admin.site.register(Book)
admin.site.register(Author)
admin.site.register(Genre)
admin.site.register(BookInstance)
python3 manage.py createsuperuser
: creates asuperuser
that has full access to the site and all needed permissions using manage.py.
Once the above command completes a new superuser will have been added to the database. Now restart the development and run the below code.
python3 manage.py runserver
Logging in and using the site
Open the /admin URL http://127.0.0.1:8000/admin
and enter new superuser userid and password credentials. This will direct you to the login page, and back to the /admin URL after the details have been entered.
From here you can add books, create new authors or genres. Once you finished add books, click save and then Home and then Books to view current list of books.
Things I want to know more about
I’m just ready to code this to see it in action.