from decimal import Decimal from django.contrib.auth import get_user_model from django.db import models User = get_user_model() 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): class Meta: unique_together = ("user", "name") user = models.ForeignKey( to=User, on_delete=models.CASCADE, editable=False, related_name="subjects", related_query_name="subject", ) name = models.CharField(max_length=64) 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", )