Django教程-如何使用 F() 表达式
什么是查询表达式?
F() 表达式
student = Student.objects.all()for stu in student:stu.fees *= 1.2
👉点击领取:最全Python资料合集
我们可以使用F() 表达式在单个查询中完成这个操作:
from django.db.models import FStudent.objects.update(fees=F('fees') * 1.2)
student = Student.objects.get(pk=1)student.price = F('fees') * 1.2student.save()
student.fees # fees = Decimal('10.00')student.fees = F('fees') + 1student.save() # fees = Decimal('11.00')student.name = 'What the F()'student.save() # fees = Decimal('12.00')
student.fees= F('fees') + 1product.save()print(student.fees) # <CombinedExpression: F(price) + Value(1)>product.refresh_from_db()print(student.fees)
from django.db.models import ExpressionWrapper, DecimalFieldProduct.objects.all().annotate(value_in_stock=ExpressionWrapper(F('fees') * F('rollno'), output_field=DecimalField()))
Student.objects.filter(fees__gte=F(2000))
帮助我们通过数据库获取数据,并限制Python访问数据库的方式。 帮助减少特定操作的查询次数。
使用F() 避免竞态条件
使用F() 对空值进行排序
from django.db.models import FStudent.objects.order_by(F('fees_paid').desc(nulls_last=True))
Func() 表达式
from django.db.models import F, Funcqueryset.annotate(field_lower=Func(F('field'), function='LOWER'))
聚合表达式
from django.db.models import CountStudent.objects.annotate(managers_required=(Count('num_employees') /8 ) + Count('num_managers'))