from decimal import Decimal from django.db import models from django.utils import timezone class PriceField(models.DecimalField): # allowing numbers until 99,999.99 max_digits = 7 decimal_places = 2 def to_python(self, value): value = super().to_python(value) if isinstance(value, Decimal): return value.quantize(Decimal(10) ** -self.decimal_places) return value def __init__(self, *args, **kwargs): kwargs['max_digits'] = self.max_digits kwargs['decimal_places'] = self.decimal_places super().__init__(*args, **kwargs) class Subject(models.Model): name = models.CharField(max_length=64) created_time = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Transaction(models.Model): class Meta: get_latest_by = "booking_date" amount = PriceField() booking_date = models.DateField() subject = models.ForeignKey( to=Subject, on_delete=models.CASCADE, related_name="transactions", related_query_name="transaction", ) class Balance(models.Model): class Meta: get_latest_by = "date" amount = PriceField() date = models.DateField()