Model Test Example
A snippet showing how to test Django model methods.
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=8, decimal_places=2, default=0)
def discount(self, pct):
return self.price * (1 - pct)
# admin.py
from django.contrib import admin
from .models import Product
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ("name", "price")
# Result (tests/test_models.py)
from django.test import TestCase
from decimal import Decimal
from .models import Product
class ProductModelTest(TestCase):
def test_discount(self):
p = Product.objects.create(name="P", price=Decimal("100.00"))
self.assertEqual(p.discount(Decimal("0.10")), Decimal("90.00"))
Explanation:
- Focus on model methods and constraints to keep domain logic correct.
-
Use
Decimalfor money to avoid float rounding surprises.
- Category Testing
- Total Views 309
- Last Modified 14 March, 2026
- Tags #testing #models #unittest #django
Previous snippet
Testing Views with Test Client
Next snippet