赞
踩
F
对象非常强大,可以在查询和更新操作中进行复杂的字段间运算。
假设我们有一个包含商品信息的模型 Product
:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
discount_price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
def __str__(self):
return self.name
获取所有折扣价低于原价的商品:
from django.db.models import F
# 获取所有折扣价低于原价的商品
discounted_products = Product.objects.filter(discount_price__lt=F('price'))
for product in discounted_products:
print(product.name, product.price, product.discount_price)
计算每个商品的折扣金额(原价减去折扣价),并按折扣金额排序:
# 计算每个商品的折扣金额,并按折扣金额排序
products_with_discount = Product.objects.annotate(
discount_amount=F('price') - F('discount_price')
).order_by('-discount_amount')
for product in products_with_discount:
print(product.name, product.price, product.discount_price, product.discount_amount)
F
对象进行更新操作将所有库存少于10的商品的价格提高10%:
# 将所有库存少于10的商品的价格提高10%
Product.objects.filter(stock__lt=10).update(price=F('price') * 1.10)
F
对象和聚合函数计算库存大于20的商品的平均折扣金额:
from django.db.models import Avg
# 计算库存大于20的商品的平均折扣金额
average_discount = Product.objects.filter(stock__gt=20).annotate(
discount_amount=F('price') - F('discount_price')
).aggregate(Avg('discount_amount'))
print(average_discount) # 输出: {'discount_amount__avg': 例如 15.00}
F
对象进行条件更新将所有库存少于10的商品的折扣价设置为原价的90%:
# 将所有库存少于10的商品的折扣价设置为原价的90%
Product.objects.filter(stock__lt=10).update(discount_price=F('price') * 0.90)
F
对象进行字段间比较和过滤获取所有折扣金额大于20的商品:
# 获取所有折扣金额大于20的商品
products_with_large_discount = Product.objects.annotate(
discount_amount=F('price') - F('discount_price')
).filter(discount_amount__gt=20)
for product in products_with_large_discount:
print(product.name, product.price, product.discount_price, product.discount_amount)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。