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

Product Model Definition

easy43%15 of 35 solved

Problem statement

A shop needs to store products, but the current model loses data: prices come back wrong, names have no length limit, and nothing records when a product was added. Redefine the Product model in app/models.py with the correct field types, constraints and string representation so that every value stored is returned unchanged and invalid values are rejected at the model layer.

Sample Data

A product row the shop needs to store faithfully:

namepricestockis_activecreated_at
Laptop19.993Trueset automatically at insert time

The current model stores price as a float, so 19.99 comes back as 19.989999...; name is unbounded, so a 500-character name is accepted; and created_at is never populated.

Requirements

Only app/models.py needs to change. Choosing the right Django field type for each column is part of the task.

1. name

  • Text of at most 100 characters; a 101-character name is rejected by validation.
  • Stored and returned unchanged.

2. price

  • An exact money amount: at most 10 digits in total, exactly 2 of them after the decimal point.
  • Stored and returned as a Decimal with no floating-point drift: Decimal("19.99") comes back as exactly Decimal("19.99").
  • A negative price is invalid; Decimal("0.00") is valid. The error is reported on the price field (a field validator), not as a model-wide error.
  • A value with more than two decimal places, or more than ten digits in total, is also invalid.

3. stock

  • A whole number that can never be negative, defaulting to 0 when no stock count is given. Pick the built-in Django field type made for non-negative whole numbers.

4. is_active

  • A true/false flag, True unless set otherwise.

5. created_at

  • A date and time filled in automatically when the row is first inserted. It never changes on later saves and cannot be edited in forms or the admin.

6. __str__

  • Returns "<name> - $<price>" with the price always shown with two decimal places: "Laptop - $19.99", and "Pen - $5.00" for a price of Decimal("5").

How validation runs

Validation rules (max length, max digits, decimal places, validators) are checked by full_clean(). save() and objects.create() do not call full_clean(), so call full_clean() to run them. The exceptions are rules the database itself enforces (for example the column type chosen for stock), which apply on every save.

Sample Requests & Responses
>>> from decimal import Decimal
>>> from app.models import Product

>>> product = Product.objects.create(name="Laptop", price=Decimal("19.99"), stock=3) >>> product.refresh_from_db() >>> product.price Decimal('19.99') >>> product.stock 3 >>> product.is_active True >>> product.created_at datetime.datetime(...) # the insert time, in UTC >>> str(product) 'Laptop - $19.99' >>> str(Product(name="Pen", price=Decimal("5"))) 'Pen - $5.00'

>>> Product.objects.create(name="Cable", price=Decimal("2.50")).stock 0

>>> Product(name="x" * 101, price=Decimal("1.00"), stock=1).full_clean() ValidationError: {'name': ['Ensure this value has at most 100 characters (it has 101).']}

>>> Product(name="Refund", price=Decimal("-0.01"), stock=1).full_clean() ValidationError: {'price': ['Ensure this value is greater than or equal to 0.']}

>>> Product(name="Fraction", price=Decimal("1.999"), stock=1).full_clean() ValidationError: {'price': ['Ensure that there are no more than 2 decimal places.']}

More in Models & Relationships

See the module
Author 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 solvedeasyLibrary Domain SchemaModel a library from scratch: members, books, authors, loans and member cards. Use every relationship kind: books to authors (many-to-many), loans that link a member and a book and carry their own due date, and one card per member, with delete rules and readable string forms throughout.56%5 of 9 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.