Skip to the content.

Code 401 Class 27 Reading Notes

Using Models

Common Field Arguments

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:
    ordering = ['-my_field_name']
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 a superuser 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.

It's Happening

<—BACK