简体   繁体   中英

Django @staticmethod sum of two fields

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.

@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.

从您与模型实例的交互方式来看,我相信您实际上想要使用@property装饰器。

You need to call this with passing the instance as parameter as below.

 total = model.fee_total(model)

The static method does not pass implicit self as instance parameter.

However, as 'Filip Dupanović' suggested you may want to use @property instead of @staticmethod

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM