本文首發於公眾號:Hunter後端 原文鏈接:Django筆記二十六之資料庫函數之數學公式函數 這一篇來介紹一下公式函數,主要是數學公式。 其中 sin,cos 這種大多數情況下用不上的就不介紹了,主要介紹下麵幾種: Abs() 絕對值 Ceil() 向上取整 Floor() 向下取整 Mod() ...
本文首發於公眾號:Hunter後端
原文鏈接: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)
以上就是本篇筆記全部內容,下一篇將介紹資料庫函數之文本函數。
如果想獲取更多後端相關文章,可掃碼關註閱讀: