这一篇来介绍一下公式函数,次要是数学公式。

其中 sin,cos 这种大多数状况下用不上的就不介绍了,次要介绍上面几种:

  1. Abs() 绝对值
  2. Ceil() 向上取整
  3. Floor() 向下取整
  4. Mod() 取余
  5. Power() 乘方
  6. Round() 四舍五入
  7. Sqrt() 获取平方根

咱们用到上面这个 model:

class MathFunction(models.Model):    x = models.FloatField(null=True, default=None)    y = models.FloatField(null=True, default=None)

1、Abs() 绝对值

先来创立一下数据:

from blog.models import MathFunctionMathFunction.objects.create(x=1.2, y=-6.3)

应用绝对值的函数:

from django.db.models.functions import Absobj = MathFunction.objects.annotate(x_abs=Abs('x'), y_abs=Abs('y')).get(id=1)print(obj.x_abs)print(obj.y_abs)

也能够在过滤的时候用该函数,然而须要先将这个函数注册,应用办法如下:

from django.db.models import FloatFieldfrom django.db.models.functions import AbsFloatField.register_lookup(Abs)MathFunction.objects.filter(x__abs__lte=2)

2、Ceil() 向上取整

向上取整
和绝对值一样,能够在取数和过滤的时候应用

取值:

from django.db.models.functions import Ceilobj = MathFunction.objects.annotate(x_ceil=Ceil('x'), y_ceil=Ceil('y')).get(id=1)print(obj.x_ceil)print(obj.y_ceil)

过滤:

from django.db.models import FloatFieldfrom django.db.models.functions import CeilFloatField.register_lookup(Ceil)MathFunction.objects.filter(x__ceil=2)

3、Floor() 向下取整

向下取整,应用办法同向上取整。

4、Mod() 取余

取模,也就是取余,两个数相除之后的余数。

MathFunction.objects.create(x=3.6, y=1.1)from django.db.models.functions import Modobj = MathFunction.objects.annotate(mod=Mod('x', 'y')).get(id=2)print(obj.mod)

其成果等效于 x % y

5、Power() 乘方

乘方,Power('x', 'y') 相当于 x ** y

MathFunction.objects.create(x=3, y=2)from django.db.models.functions import Powerobj = MathFunction.objects.annotate(power=Power('x', 'y')).get(id=3)print(obj.power)

6、Round() 四舍五入

四舍五入,示例如下:

from django.db.models.functions import Roundobj = MathFunction.objects.annotate(    x_round=Round('x'),    y_round=Round('y')).get(id=1)print(obj.x_round)print(obj.y_round)

7、Sqrt() 获取平方根

MathFunction.objects.create(x=9, y=25)from django.db.models.functions import Sqrtobj = MathFunction.objects.annotate(x_sqrt=Sqrt('x'), y_sqrt=Sqrt('y')).get(id=4)print(obj.x_sqrt)print(obj.y_sqrt)

以上就是本篇笔记全部内容,下一篇将介绍数据库函数之文本函数。

本文首发于自己微信公众号:Django笔记。

原文链接:Django笔记二十六之数据库函数之数学公式函数

如果想获取更多相干文章,可扫码关注浏览: