I have a quick question. I’m trying to add a field to a model which is the sum of 2 fields.
For example:
class MyModel(models.Model)
fee = models.DecimalField()
fee_gst = models.DecimalField()
I thought I could just add a @staticmethod inside the model:
@staticmethod
def fee_total(self):
return self.fee + self.fee_gst
But I can’t seem to access the “fee_total” field of the model using:
model = MyModel.objects.get(pk=1)
total = model.fee_total
Any ideas what I’m doing wrong?
Cheers
I think you want to add a method to your model so this https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods might help you.
@staticmethodis a decorator that declares method to theclass, so whats the difference?Well long story short, static methods don’t have instances to any particular object just an instance to the
classObject, what do I mean byclassobject, most things in python like functions, class, and of course instances of objects are actually objects …Like everyone has mentioned before
@propertyis a decorator that lets a method act as variable … so you don’t have to explicitly use()eitherway, you would want to do this:
though the docs take a longer approach:
both methods are pretty much equivalent though we use the decorator as a short-hand.
hope this helps.