0
0
Djangoframework~30 mins

Testing models in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing models in Django
📖 Scenario: You are building a simple Django app to manage books in a library. You want to make sure your Book model works correctly by writing tests.
🎯 Goal: Write tests for the Book model to check that it saves and retrieves data correctly.
📋 What You'll Learn
Create a Book model with fields title and author
Add a test case class for the Book model
Write a test method to create and save a Book instance
Write a test method to retrieve the saved Book and check its fields
💡 Why This Matters
🌍 Real World
Testing models ensures your data structure works correctly before your app runs in production. It helps catch bugs early.
💼 Career
Writing model tests is a key skill for Django developers to maintain reliable and maintainable codebases.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with two fields: title as a CharField with max length 100, and author as a CharField with max length 50.
Django
Need a hint?

Use models.CharField for text fields and set max_length as instructed.

2
Set up the test case class
Create a test case class called BookModelTest that inherits from django.test.TestCase.
Django
Need a hint?

Import TestCase from django.test and create an empty test class.

3
Write a test to create and save a Book
Inside the BookModelTest class, write a test method called test_create_book that creates a Book instance with title set to 'Django for Beginners' and author set to 'William S. Vincent', then saves it.
Django
Need a hint?

Define a method starting with test_ inside the test class. Create and save the Book instance inside it.

4
Write a test to retrieve and check the Book
Add a test method called test_retrieve_book inside BookModelTest that retrieves the saved Book by filtering title='Django for Beginners' and asserts that the author is 'William S. Vincent' using self.assertEqual.
Django
Need a hint?

Use Book.objects.get() to find the book and self.assertEqual() to check the author.