【发布时间】:2016-06-21 02:42:22
【问题描述】:
目标是创建一个custom_filter 方法,该方法可以链接到标准的 Django 过滤器方法。 custom_filter 方法可能需要一些原始 SQL 代码。在最好的情况下,QuerySet 仍然会被评估为惰性。
最后,这样的命令会很棒:
apple_query_set = Apple.objects.filter(<any standard filtering>).custom_filter()
这是模型:
class Apple(models.model):
a = models.IntegerField()
b = models.IntegerField()
date = models.DateField()
custom_filter 的目标是按 (a,b) 对 Apple 实例进行分组,并为每个
group 根据date只返回最新的实例。
此类过滤器的原始 SQL 代码如下:
custom_filter_raw_sql = """
SELECT t1.id
FROM app_apple AS t1
INNER JOIN (SELECT a, b, max(date) AS max_date
FROM app_apple
GROUP BY a, b) AS t2
ON t1.a = t2.a AND t1.b = t2.b AND t1.date = t2.max_date;
"""
到目前为止,为了添加custom_filter 功能,
我已经尝试(不成功)将objects = AppleQuerySet.as_manager() 添加到 Apple 类中,其中:
class AppleQuerySet(models.QuerySet):
def custom_filter(self):
subquery = """
SELECT t1.id
FROM app_apple AS t1
INNER JOIN (SELECT a, b, max(date) AS max_date
FROM app_apple
GROUP BY a, b) AS t2
"""
condition = "t1.a = t2.a AND t1.b = t2.b AND t1.date = t2.max_date"
return self.extra(tables=[subquery], where=[condition])
但是,我不确定这种方法是否可行,因为自定义查询
不仅应该适用于所有 Apple 实例 (Apple.objects.),而且应该可以将其链接到过滤后的查询集 (Apple.objects.filter())
创建此自定义可链接(惰性)custom_filter 功能的最佳方法是什么?我哪里错了?非常感谢!
【问题讨论】:
-
是否有特定原因不能通过使用查询本身的所有过滤条件直接perform raw queries?
-
@AKS 这可能是一个解决方案,但我不知道如何确保 SQL 代码可以任意链接到 QuerySet(而不是对整个 Apple 表进行过滤)。我很高兴看到一些代码如何做到这一点。 (另外,我不确定这个解决方案是否允许惰性评估。)
标签: python sql django filter django-queryset