【发布时间】:2016-03-02 14:32:10
【问题描述】:
我在mysql中有下表
这是模型:
class cube(models.Model):
pid = models.IntegerField()
av = models.CharField(max_length=100)
sid = models.IntegerField()
st = models.IntegerField()
我想要实现的是我想知道 pid 的列表有
(sid=1,st>=5) and (sid=2,st>=7)
根据屏幕截图,这应该会从我的表中产生两个 pid - 3214 和 3215。 pid 3213 不满足条件,所以不返回。
我正在尝试以下方法来实现我在 View 中的要求:
查看代码:
testq=(cube.objects.filter((Q(sid='1') & Q(srt_gte="5")) & (Q(sid='2') & Q(srt_gte="7")))
也尝试以这种方式使用 lambda -
input = [{"sid":1,"st":5},{"sid":2,"st":7}]
queries = [Q(sid=i['sid'], st__gte=i['st']) for i in input]
sid_query = reduce(lambda x, y: ________ , queries)
在上面的 lambda 中,我尝试使用 case 语句,例如 (λx: 1 如果查询其他 0 )
queryset=cube.objects.values_list('pid').filter(sid_query).annotate('pid')
这不起作用:(
尝试了以下其他方式:
testq=cube.objects.filter(Q(sid__in=[1,2])& (Q(srt__gte=[5,7]))).annotate(c=Count('sid')).filter(c=2)
看来这是错误的。
无法弄清楚如何根据我的要求获得结果。
List of pid's who has (sid=1,st>=5) and (sid=2,st>=7)
以下是该要求的等效 SQL:
select b.pid
from cube b
group by b.pid
having sum(case when (b.sid = 1) and (b.srt >= 5) then 1 else 0 end) > 0 AND
sum(case when (b.sid = 2) and (b.srt >= 7) then 1 else 0 end) > 0;
【问题讨论】:
标签: django python-3.x lambda django-views