【问题标题】:How to call a custom method with arguments in the models.py from views.py如何在views.py的models.py中调用带有参数的自定义方法
【发布时间】:2016-06-12 03:41:20
【问题描述】:

我有这个例子:

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

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

在视图中:

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

    # More code...

这是一个非常简单的例子,因为我想做类似的事情,那么我该怎么做呢?

谢谢!

【问题讨论】:

  • 在不相关的评论中,您可能希望使用 DecimalField 而不是 FloatField 来节省价格。

标签: django python-2.7 django-models django-views django-1.9


【解决方案1】:

您需要在for 循环中执行此操作,因为m 是一个对象数组:

for item in m:
     result = item.calculate(any_number)
    # do some stuff with the result

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-07-26
  • 2016-02-18
  • 2019-11-22
  • 2019-11-19
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多