我的Django模型中有以下字段
class cube(models.Model):
pid = models.IntegerField()
lc = models.CharField(max_length=100)
sid = models.IntegerField()
st = models.IntegerField()
wid = models.IntegerField()
wt = models.IntegerField()
我有以下来自客户的输入集
input_set1对象 -
[{"sid":1,"st":7},{"sid":7,"st":5},{"sid":5,"st":9},{"sid":2,"st":7}]
input_set2 object -
[{"wid":3,"wt":5},{"wid":1,"wt":7},{"wid":4,"wt":8},{"wid":2,"wt":5},{"wid":5,"wt":5}]
以下是我的要求,即mysql表示法:
select pid,lc from cube
where (((sid=1) AND (st>=7)) AND ((sid=7) AND (sid>=5)) AND ((sid=5) AND
(st>=9)) AND ((sid=2) AND (st>=7)))
AND (((wid=3) AND (wt>=5)) AND ((wid=1) AND (wt>=7)) AND ((wid=4) AND
(wt>=8)) AND ((wid=2) AND (wt>=5)) AND ((wid=5) AND (wt>=5)))
输入{sid,st}和{wid,wt}集合每个最多可包含10个项目 - 像{sid,st}每个输入最多10个,{wid,wt}
相同如何在django中编写这个sql表示法?
我想在我的视图中使用输入参数作为下面的列表,这样它对输入集来说是通用的 -
input_set1=[{1,7},{7,5},{5,9},{2,7}]
input_set2=[{3,5},{1,7},{4,8},{2,5},{5,5}]
fieldsReq=['pid','lc']
queryset=cube.objects.values_list(fieldsReq).filter(reduce(operator.and_, (Q(sid__contains=x) for x in ['3', '5', '6']),(Q(rt__contains=x) for x in ['4', '8', '3']))) #Am not sure how to write the condition here
我想将input_set1映射到{sid,st} 和input_set2到{wid,wt},但发现写作有困难。
如何用Django表示法从mysql表中获取字段?
答案 0 :(得分:1)
这是我对sid
的尝试,它也适用于wid
。
from django.db.models import Q
# original input
input = [{"sid":1,"st":7},{"sid":7,"st":5},{"sid":5,"st":9},{"sid":2,"st":7}]
# a list of Q objects
queries = [Q(sid=i['sid'], st__gte=i['st']) for i in input]
# 'AND' all conditions
sid_query = reduce(lambda x, y: x & y, queries)
fieldsReq=['pid','lc']
queryset=cube.objects.values_list(fieldsReq).filter(sid_query)