django - 如何在 Django 中创建引用两个相关模型的注释
问题描述
当一个相关对象上的字段值小于另一个相关对象上的字段值时,我正在尝试向 QuerySet 添加注释,该注释为 True/False。
以下是一些模型示例:
class RobotManager(models.Manager):
queryset = super(RobotManager, self).get_queryset()
queryset = queryset.annotate(canteen_empty=UNKNOWN CODE)
return queryset
class Robot(models.Model):
# Has some other unrelated stuff
objects = RobotManager()
class CanteenLevel(models.Model):
time = models.DateTimeField()
robot = models.ForeignKey("SomeApp.Robot")
gallons = models.IntegerField()
class RobotConfiguration(models.Model):
time = models.DateTimeField()
robot = models.ForeignKey("SomeApp.Robot")
canteen_empty_level = models.IntegerField()
使用上述模型,随着机器人的配置或食堂级别的变化,我们会创建新的记录并保存历史记录。
我想做的是向机器人查询集添加一个注释,说明机器人的食堂是否被认为是空的(机器人的最新 CanteenLevel.gallons 小于机器人的最新 Configuration.canteen_empty_level)。
目的是允许使用 QuerySet 中的注释进行这样的语句:
bad_robots = Robot.objects.filter(canteen_empty=True)
我在注释中尝试过这样的事情:
canteen_empty=ExpressionWrapper(CanteenLevel.objects.filter(robot=OuterRef('pk')).order_by('-time').values('gallons')[:1] <= RobotConfiguration.objects.filter(robot=OuterRef('robot')).order_by('-time').values('canteen_empty_level')[:1], output_field=models.BooleanField))
但显然“<=”运算符是不允许的。
我也试过这个:
canteen_empty=Exists(CanteenLevel.objects.filter(robot=OuterRef('pk')).order_by('-time').values('gallons')[:1].filter(gallons__lte=Subquery(RobotConfiguration.objects.filter(robot=OuterRef('robot')).order_by('-time').values('canteen_empty_level')[:1]))))
但是你不能在获取一个 QuerySet 之后进行过滤。
任何帮助,将不胜感激!
解决方案
我们可以在这里做两个注解:
from django.db.models import Subquery, OuterRef
latest_gallons = Subquery(CanteenLevel.objects.filter(
robot=OuterRef('pk')
).order_by('-time').values('gallons')[:1])
latest_canteen = Subquery(RobotConfiguration.objects.filter(
robot=OuterRef('pk')
).order_by('-time').values('canteen_empty_level')[:1])
然后我们可以先用这些注释Robot
对象,然后过滤:
from django.db.models import F
Robot.objects.annotate(
latest_gallons=latest_gallons,
latest_canteen=latest_canteen
).filter(latest_gallons__lte=F('latest_canteen'))
这将构造一个如下所示的查询:
SELECT robot.*,
(SELECT U0.gallons
FROM canteenlevel U0
WHERE U0.robot_id = robot.id
ORDER BY U0.time DESC
LIMIT 1) AS latest_gallons,
(SELECT U0.canteen_empty_level
FROM robotconfiguration U0
WHERE U0.robot_id = robot.id
ORDER BY U0.time DESC
LIMIT 1) AS latest_canteen
FROM robot
WHERE
(SELECT U0.gallons
FROM canteenlevel U0
WHERE U0.robot_id = robot.id
ORDER BY U0.time DESC
LIMIT 1
) <= (
SELECT U0.canteen_empty_level
FROM robotconfiguration U0
WHERE U0.robot_id = robot.id
ORDER BY U0.time DESC
LIMIT 1
)
但是请注意,如果 aRobot
没有相关的CanteenLevel
,或RobotConfiguration
(其中之一,或两者),那么Robot
它将不会包含在查询集中。
推荐阅读
- reactjs - React grid layout not working with firebase
- haskell - Compile Haskell program with third-party dependencies
- java - How Do I Mark A RequestParam As Optional In Swagger?
- python - "module 'torchtext.data' has no attribute 'Field'"
- javascript - how to call a function with a submit element
- android - HDR gradient on Android not possible?
- math - 将平面转换为 XY 平面
- sql - 获取 Time 的每日行数
- entity-relationship - 具有两个参与者的 ER 建模帐户交易
- c++ - 调用包含的对象函数时,std::optional 是否转发右值?