“ 这是Django系列笔记的第二十六篇,文章内容均为本人通过阅读Django官方文档后整理所得,可用作新手入门指南,或者个人知识点查阅。”
这一篇来介绍一下公式函数,主要是数学公式。
其中 sin,cos 这种大多数情况下用不上的就不介绍了,主要介绍下面几种:
-
Abs() 绝对值 -
Ceil() 向上取整 -
Floor() 向下取整 -
Mod() 取余 -
Power() 乘方 -
Round() 四舍五入 -
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 MathFunction
MathFunction.objects.create(x=1.2, y=-6.3)
使用绝对值的函数:
from django.db.models.functions import Abs
obj = 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 FloatField
from django.db.models.functions import Abs
FloatField.register_lookup(Abs)
MathFunction.objects.filter(x__abs__lte=2)
2、Ceil() 向上取整
向上取整和绝对值一样,可以在取数和过滤的时候使用
取值:
from django.db.models.functions import Ceil
obj = 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 FloatField
from django.db.models.functions import Ceil
FloatField.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 Mod
obj = 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 Power
obj = MathFunction.objects.annotate(power=Power('x', 'y')).get(id=3)
print(obj.power)
6、Round() 四舍五入
四舍五入,示例如下:
from django.db.models.functions import Round
obj = 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 Sqrt
obj = MathFunction.objects.annotate(x_sqrt=Sqrt('x'), y_sqrt=Sqrt('y')).get(id=4)
print(obj.x_sqrt)
print(obj.y_sqrt)
以上就是本篇笔记全部内容,下一篇将介绍数据库函数之文本函数。
如果感兴趣,可以点击下方关注后续…
原文始发于微信公众号(Hunter后端):Django笔记二十六之数据库函数之数学公式函数
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/178860.html