需要使用django中的F
先看看模型,这是一个用户订阅记录模块,就和QQ会员记录那种似的:
class Subscribe(Object):
download_total = models.IntegerField(default=0,)
download_used = models.IntegerField(default=0,)
expires_time = models.DateTimeField(default="")
is_expires = models.BooleanField(default=False,)
order = models.OneToOneField(to=Order, related_name="order", on_delete=models.PROTECT)
product = models.ForeignKey(to="Product", related_name="subscribes",
on_delete=models.PROTECT,)
user = models.ForeignKey(to="user.User", related_name="subscribes",
on_delete=models.PROTECT,)
def __str__(self):
return "{}".format(self.uuid)
class Meta:
db_table = "subscribe"
verbose_name = verbose_name_plural = "订阅"
例如,要在SQL中执行的操作,需要用ORM来实现
SQL:
select * from subscribe where download_total > download_used
ORM:
from django.db.models import F
from .models import Test
test= Test.objects.filter(download_total__gt=F('download_used'))
当然F查询是个很强的功能,具体参见官方文档:
https://docs.djangoproject.com/en/2.2/ref/models/expressions/#f-expressions
本文详细介绍如何在Django ORM中使用F表达式进行高效数据库查询,通过对比SQL语句,展示F表达式的强大功能,如在用户订阅记录模块中过滤下载总量大于已用下载量的记录。
1105

被折叠的 条评论
为什么被折叠?



