Django @staticmethod sum of two fields

I have a quick question. I am trying to add a field to a model, which is a sum of two fields.

For instance:

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

I thought I could just add @staticmethod inside the model:

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

But I can’t 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?

Greetings

+5
source share
3 answers

I think you want to add a method to your model so that https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods can help you.

@staticmethodis a decorator that declares a method class, so what's the difference?

, - class, class, , ...

, @property - , ... ()

, :

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

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

:

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)

, .

, .

+5

, , , @.

+2

, , .

 total = model.fee_total(model)

self .

However, since 'Filip Dupanović' suggested you use @property instead of @staticmethod

0
source

All Articles