给定以下模型(使用django-simple-history
):
class MyModel (models.Model):
status = models.IntegerField()
history = HistoricalRecords()
我想获取在给定日期没有特定status
的所有实例(即在限制日期具有不同状态的所有实例,加上当时不存在的所有实例).
以下查询将返回在限制日期之前任何时候从未有status = 4
的所有实例:
MyModel.filter (~Exists (
MyModel.history.filter (
id = OuterRef ("id"),
history_date__lte = limit_date,
status = 4))
但不幸的是,它还删除了在过go 某个日期有status = 4
的实例,然后在限制日期更改为不同的status
,我想保留这些实例.
以下内容应该给出正确的结果:
MyModel.filter (~Exists (
MyModel.history.filter (
id = OuterRef ("id"),
history_date__lte = limit_date)
.order_by ("-history_date")
[:1]
.filter (status = 4)))
不幸的是,它不起作用:Cannot filter a query once a slice has been taken.
这question链接到这documentation page,这解释了在查询集被切片后不允许过滤.
请注意,错误来自Django中的assert
.如果我在django/db/models/query.py:953
中注释掉assert
,那么代码似乎有效并给出预期结果.然而,在upstream 依赖项中 comments 掉assert
并不是生产中可行的解决方案.
那么,有没有一种干净的方法可以根据对象的过go 状态过滤我的查询集呢?