0
0
Djangoframework~5 mins

Testing models in Django

Choose your learning style9 modes available
Introduction

Testing models helps make sure your data and logic work correctly. It catches mistakes early so your app stays reliable.

When you want to check if your model saves data properly.
When you need to verify custom methods on your model work as expected.
When you want to ensure your model validations prevent bad data.
When you update your model and want to confirm nothing breaks.
When you want to automate checks to save time during development.
Syntax
Django
from django.test import TestCase
from .models import YourModel

class YourModelTest(TestCase):
    def test_something(self):
        instance = YourModel(field='value')
        instance.save()
        self.assertEqual(instance.field, 'value')

Use TestCase from django.test to create test classes.

Test methods must start with test_ to run automatically.

Examples
This tests the string output of a Book model instance.
Django
from django.test import TestCase
from .models import Book

class BookModelTest(TestCase):
    def test_string_representation(self):
        book = Book(title='Django Basics')
        self.assertEqual(str(book), 'Django Basics')
This checks that the Product model raises an error if price is negative.
Django
from django.test import TestCase
from .models import Product

class ProductModelTest(TestCase):
    def test_price_positive(self):
        product = Product(price=-10)
        with self.assertRaises(Exception):
            product.full_clean()
Sample Program

This example defines an Item model with a method to check stock. The tests check if the method works and if negative quantity is invalid.

Django
from django.db import models
from django.test import TestCase

class Item(models.Model):
    name = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()

    def is_in_stock(self):
        return self.quantity > 0

class ItemModelTest(TestCase):
    def test_is_in_stock(self):
        item = Item(name='Pen', quantity=10)
        self.assertTrue(item.is_in_stock())

    def test_quantity_cannot_be_negative(self):
        item = Item(name='Notebook', quantity=-5)
        with self.assertRaises(Exception):
            item.full_clean()
OutputSuccess
Important Notes

Use full_clean() to run model validations in tests.

Test database is separate and resets after tests run.

Run tests with python manage.py test.

Summary

Testing models ensures your data logic is correct.

Use Django's TestCase and write methods starting with test_.

Check both data saving and custom model methods.