Trong tập này, bạn sẽ thiết kế 3 models cốt lõi của ứng dụng quản lý chi tiêu — Category (danh mục), Transaction (giao dịch thu/chi) và Budget (ngân sách) — rồi sinh migrations để tạo bảng thật trong database. Kết thúc tập này, database của bạn đã có đủ bảng để lưu toàn bộ dữ liệu chi tiêu, sẵn sàng cho tập 3 tùy chỉnh Django admin. Đây là bước nối tiếp trực tiếp của tập 1 “Giới thiệu series + setup project”, nơi ta đã dựng project Django với settings tách dev/prod.

1. Tạo app expenses

Mỗi app Django nên gói gọn một nhóm chức năng liên quan. App expenses sẽ chứa toàn bộ nghiệp vụ chi tiêu:

python manage.py startapp expenses

Rồi thêm "expenses" vào INSTALLED_APPS trong settings (cấu trúc settings tách dev/prod ta đã dựng ở tập 1).

2. Model Category — danh mục thu/chi

Danh mục là xương sống của mọi báo cáo sau này: mỗi giao dịch bắt buộc thuộc về một danh mục. Ta dùng TextChoices để phân loại thu/chi ngay trong model, và UniqueConstraint để tránh trùng tên danh mục của cùng một user:

# expenses/models.py
from decimal import Decimal
from django.conf import settings
from django.core.validators import MinValueValidator
from django.db import models
from django.utils import timezone
class Category(models.Model):
class Kind(models.TextChoices):
INCOME = "income", "Thu nhập"
EXPENSE = "expense", "Chi tiêu"
name = models.CharField("tên danh mục", max_length=100)
kind = models.CharField("loại", max_length=10,
choices=Kind.choices, default=Kind.EXPENSE)
color = models.CharField("màu hiển thị", max_length=7, default="#06B6D4")
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="categories")
class Meta:
constraints = [
models.UniqueConstraint(
fields=["user", "name", "kind"],
name="uniq_category_per_user",
),
]
def __str__(self):
return f"{self.name} ({self.get_kind_display()})"

3. Model Transaction — từng khoản thu/chi

Transaction lưu từng khoản tiền phát sinh. Hai điểm quan trọng: số tiền dùng DecimalField (không bao giờ dùng FloatField cho tiền), và khóa ngoại tới Category dùng on_delete=PROTECT để không thể xóa nhầm danh mục đang có giao dịch:

class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="transactions")
category = models.ForeignKey(Category,
on_delete=models.PROTECT,
related_name="transactions",
verbose_name="danh mục")
amount = models.DecimalField("số tiền", max_digits=12, decimal_places=2,
validators=[MinValueValidator(Decimal("0.01"))])
occurred_on = models.DateField("ngày phát sinh", default=timezone.now)
note = models.CharField("ghi chú", max_length=255, blank=True)
class Meta:
ordering = ["-occurred_on", "-id"]
indexes = [
models.Index(fields=["user", "occurred_on"],
name="txn_user_date_idx"),
]
def __str__(self):
return f"{self.category.name}: {self.amount:,}đ ({self.occurred_on})"

4. Model Budget — hạn mức chi tiêu theo tháng

Budget lưu hạn mức của mỗi danh mục cho từng tháng. UniqueConstraint đảm bảo mỗi bộ (user, danh mục, năm, tháng) chỉ có một hạn mức; CheckConstraint khóa giá trị tháng trong khoảng 1–12:

class Budget(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="budgets")
category = models.ForeignKey(Category,
on_delete=models.CASCADE,
related_name="budgets",
verbose_name="danh mục")
year = models.PositiveIntegerField("năm")
month = models.PositiveSmallIntegerField("tháng")
amount = models.DecimalField("hạn mức", max_digits=12, decimal_places=2,
validators=[MinValueValidator(Decimal("0.01"))])
class Meta:
constraints = [
models.UniqueConstraint(
fields=["user", "category", "year", "month"],
name="uniq_budget_per_month",
),
models.CheckConstraint(
condition=models.Q(month__gte=1, month__lte=12),
name="budget_month_range",
),
]
def __str__(self):
return f"{self.category.name} {self.month:02d}/{self.year}: {self.amount:,}đ"

5. Sinh migrations và tạo bảng

Ba lệnh quen thuộc, nhưng đừng bỏ qua sqlmigrate — nó cho bạn thấy Django sẽ chạy SQL gì trước khi chạm vào database:

python manage.py makemigrations expenses
python manage.py sqlmigrate expenses 0001
python manage.py migrate

Kiểm tra nhanh trong shell rằng bảng đã hoạt động:

python manage.py shell
>>> from expenses.models import Category
>>> Category.objects.count()
0

Áp dụng vào dự án của bạn

Đừng vội tạo model thứ tư. Hầu hết nhu cầu mở rộng — ảnh hóa đơn (thêm ImageField vào Transaction), giao dịch định kỳ như tiền nhà (thêm BooleanField recurring), lọc chéo theo nhãn (thêm ManyToManyField tới model Tag) — đều chỉ là thêm trường vào 3 models này. Quy tắc vàng với dữ liệu tiền bạc: xóa mềm bằng cờ is_active thay vì xóa cứng, và giữ PROTECT cho khóa ngoại danh mục để một cú click dọn dẹp không cuốn trôi cả lịch sử chi tiêu.

Bài viết liên quan

Câu hỏi thường gặp

Vì sao dùng DecimalField thay vì FloatField cho số tiền?

Float lưu số theo hệ nhị phân nên 0.1 + 0.2 ra 0.30000000000000004 — sai số này nhân lên qua hàng nghìn giao dịch sẽ làm lệch sổ. DecimalField lưu chính xác theo hệ thập phân, đúng chuẩn kế toán.

on_delete=models.PROTECT khác CASCADE ở điểm nào?

PROTECT chặn thao tác xóa danh mục khi còn giao dịch liên quan và ném ProtectedError — an toàn cho dữ liệu tài chính. CASCADE xóa luôn toàn bộ giao dịch theo, chỉ nên dùng khi bạn thật sự muốn xóa theo (ví dụ xóa user thì xóa hết dữ liệu của họ).

Có cần gắn user vào models ngay từ bây giờ không?

Có. Ở tập 8 ta thêm đăng nhập JWT và mỗi user chỉ thấy dữ liệu của mình. Gắn ForeignKey tới user ngay từ đầu giúp dữ liệu tách biệt từ ngày đầu, tránh migration chuyển đổi phức tạp khi app đã có dữ liệu thật.

UniqueConstraint và unique_together khác nhau thế nào?

unique_together đã bị deprecated — cách chuẩn hiện nay là khai báo models.UniqueConstraint trong Meta.constraints, mạnh hơn vì hỗ trợ cả điều kiện (condition) và tên ràng buộc rõ ràng trong database.

Đổi model rồi quên chạy migrations thì sao?

Chạy python manage.py makemigrations rồi migrate. Muốn xem app nào đã migrate tới đâu, dùng python manage.py showmigrations — dấu [X] nghĩa là migration đã được áp dụng.

Nguồn tham khảo