StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 1 · Models & Relationships

Library Domain Schema

easy56%5 of 9 solved

Problem statement

A library system needs its whole domain modeled from scratch: members, books, authors, loans, and member cards. app/models.py declares the five models as empty shells; your task is to give each one its fields, relationships, constraints and string representation. You choose the field types, the relationship types and what happens on delete; the requirements below describe the behaviour. Migrations are not graded. The tests build the database directly from your app/models.py (and generate the schema from it themselves), so you do not need to create or commit an app/migrations/ folder. The Run button runs makemigrations for you.

Domain Model

Five models live in app/models.py: Author, Member, MemberCard, Book, Loan. Each is currently an empty models.Model with a # Write your code here marker.

Author

FieldMeaning
namerequired text, at most 200 characters

Member

FieldMeaning
namerequired text, at most 200 characters
joined_atdate and time filled in automatically on create, never changed after

MemberCard: a member's library card

FieldMeaning
memberthe member who owns the card. A member has at most one card, reachable as member.card.
serialtext, at most 20 characters; no two cards may share a serial (enforced by the database)
is_activetrue/false flag, True unless set otherwise

Book

FieldMeaning
titlerequired text, at most 200 characters
authorsthe book's authors. A book can have many authors and an author many books; an author's books are author.books.
replacement_costexact money amount: at most 6 digits in total, exactly 2 after the decimal point; never negative
copieswhole number that can never be negative, 0 unless set otherwise
is_availabletrue/false flag, True unless set otherwise
added_atdate and time filled in automatically on create, never changed after

Loan: one member borrowing one book

FieldMeaning
memberthe borrowing member (required). A member can have many loans, reachable as member.loans.
bookthe borrowed book (required). A book can have many loans, reachable as book.loans.
due_daterequired calendar date (no time of day)
returnedtrue/false flag, False unless set otherwise

Requirements

  1. Every relation is readable from both sides by its name. author.books, member.card, member.loans and book.loans must be the reverse names of the relationships themselves, so they also work in queries such as Member.objects.filter(loans__book=book). A hand-written property with the same name does not count. The Django default names (author.book_set, member.loan_set, member.membercard) must not exist. member.card returns the card itself, and raises Member.card.RelatedObjectDoesNotExist for a member without one.
  2. Field rules. Text limits and the serial uniqueness are as in the tables. replacement_cost keeps exactly two decimal places, holds at most six digits in total, and a negative amount is invalid. Report that error on the replacement_cost field (a field validator), not as a model-wide error. Validation runs through full_clean(); save() does not call it. Defaults and automatic timestamps are as in the tables.
  3. What happens on delete.

    • Deleting a Member deletes that member's card and loans.
    • Deleting a Book that still has loans is refused with Django's ProtectedError, and nothing is deleted; once its loans are gone, the book deletes normally.
    • Deleting an Author removes the author's links to books, but the books themselves remain.
    • A Loan cannot be saved without both a member and a book.
  4. String representations.

    Modelstr(obj)Example
    Authorthe author's nameUrsula K. Le Guin
    Memberthe member's nameAda Lovelace
    MemberCardCard <serial>Card LIB-0001
    Book<title> ($<replacement_cost>), cost always with two decimal placesA Wizard of Earthsea ($15.00); Tehanu ($12.00) for Decimal("12")
    Loan<book title> -> <member name> (due <YYYY-MM-DD>)A Wizard of Earthsea -> Ada Lovelace (due 2026-03-01)
Sample Usage
>>> from datetime import date
>>> from decimal import Decimal
>>> leguin = Author.objects.create(name="Ursula K. Le Guin")
>>> earthsea = Book.objects.create(title="A Wizard of Earthsea", replacement_cost=Decimal("15.00"))
>>> earthsea.authors.add(leguin)
>>> list(leguin.books.values_list("title", flat=True))
['A Wizard of Earthsea']
>>> ada = Member.objects.create(name="Ada Lovelace")
>>> MemberCard.objects.create(member=ada, serial="LIB-0001")
<MemberCard: Card LIB-0001>
>>> ada.card.is_active
True
>>> loan = Loan.objects.create(member=ada, book=earthsea, due_date=date(2026, 3, 1))
>>> str(loan)
'A Wizard of Earthsea -> Ada Lovelace (due 2026-03-01)'
>>> earthsea.delete()          # blocked: the loan still references it
django.db.models.deletion.ProtectedError: ...
>>> ada.delete()               # cascades to the card and the loan
>>> earthsea.delete()          # now allowed

More in Models & Relationships

See the module
Product Model DefinitionProducts lose data: prices come back wrong, names have no length limit, and nothing records when an item was added. Define a Product model with a bounded name, an exact decimal price, a stock count with a sensible default, an active flag, an auto-set creation time and a readable string form.43%15 of 35 solvedeasyAuthor Book Foreign KeyBooks and authors live in unrelated tables, so deleting an author leaves orphaned books. Relate Book to Author so an author's books go with the author and are listed through the author, and add an optional publisher that cannot be deleted while it still has books.100%9 of 9 solvedeasyCourse Enrollment LinksStudents take many courses, courses have many students, and each student has exactly one transcript. Model the many-to-many and the one-to-one, readable from both sides, with at most one transcript per student enforced by the database.83%5 of 6 solvedeasy

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.