MiddleCodeCommonNot answered yet
Refactor two Django models duplicating amount fields and to_dict
Two models duplicate the same four amount_* fields and a to_dict method. Refactor to remove the duplication. Also review the field choices.
class PassengerAmount(models.Model):
amount_buy = models.FloatField(null=True)
amount_buy_currency_code = models.CharField(null=True, max_length=3)
amount_sell = models.FloatField(null=True)
amount_sell_currency_code = models.CharField(null=True, max_length=3)
def to_dict(self): ...
class BookingAmount(models.Model):
# same four amount_* fields + status + identifier
def to_dict(self): ...
Refactor the models and note any correctness problems.
Pull the shared amount_* fields and to_dict into an abstract base model — class AmountBase(models.Model): ... with class Meta: abstract = True — and have both models inherit it; abstract bases create no table, only inherited columns. The key correctness fix: money as FloatField is a bug (binary float rounding) — use DecimalField. Also reconsider the loose null=True on amount/currency fields.
- ✗Using concrete inheritance instead of an abstract base
- ✗Keeping
FloatFieldfor money instead ofDecimalField - ✗Forgetting
class Meta: abstract = Trueso a spurious table is created
- →Why is
FloatFieldwrong for money andDecimalFieldright? - →How does an abstract base model differ from multi-table inheritance?