-2

I have this example:

class MyModel(models.Model):
    # Some fields...
    price = models.FloatField()

    def calculate(self, number):
        return self.price * number

In the views:

def whatever(request, any_number):
    m = MyModel.objects.all()
    c = m.calculate(any_number)

    # More code...

It's a really easy example because I want to do something similar, so how can I do this?

Thank you!

hectorlr22
  • 123
  • 1
  • 9
  • 1
    In an unrelated comment, you probably want to use a DecimalField instead of a FloatField for saving prices. – krs Feb 29 '16 at 08:04

1 Answers1

1

You need to do it in a for loop, since m is an array of objects:

for item in m:
     result = item.calculate(any_number)
    # do some stuff with the result
chem1st
  • 1,624
  • 1
  • 16
  • 22
  • 1
    That, or define the method in a custom manager. https://docs.djangoproject.com/en/1.9/topics/db/managers/ – Wtower Feb 29 '16 at 09:44