Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django @staticmethod sum of two fields

Tags:

python

django

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

like image 512
Ben Kilah Avatar asked Jul 12 '12 06:07

Ben Kilah


1 Answers

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.

@staticmethod is a decorator that declares method to the class, so whats the difference?

Well long story short, static methods don't have instances to any particular object just an instance to the class Object, what do I mean by class object, most things in python like functions, class, and of course instances of objects are actually objects ...

Like everyone has mentioned before @property is a decorator that lets a method act as variable ... so you don't have to explicitly use ()

eitherway, you would want to do this:

class MyModel(models.Model)
    fee = models.DecimalField()
    fee_gst = models.DecimalField()

    @property        
    def fee_total(self):
        return self.fee + self.fee_gst 

though the docs take a longer approach:

class MyModel(models.Model)
    fee = models.DecimalField()
    fee_gst = models.DecimalField()


    def _fee_total(self):
        return self.fee + self.fee_gst
    fee_total = property(_fee_total)

both methods are pretty much equivalent though we use the decorator as a short-hand.

hope this helps.

like image 72
Samy Vilar Avatar answered Oct 08 '22 20:10

Samy Vilar