如何将查询转换为django ORM

时间:2016-08-11 06:04:59

标签: python django django-models

SELECT * FROM mytable
WHERE 
'2016-08-05' BETWEEN from_date AND COALESCE(to_date,CURDATE()) 
OR 
'2016-08-11' BETWEEN from_date AND COALESCE(to_date,CURDATE()

上面是mysql中的查询。如何在Django中编写此查询? MyTable 是Django中映射到MySQL mytable 表的对象的名称

1 个答案:

答案 0 :(得分:1)

最简单的方法

了解Raw SQL

MyTable.objects.raw(your_sql)

更复杂

了解QuerySet.extra

MyTable.objects.all().extra(where="'2016-08-05' BETWEEN from_date AND COALESCE(to_date,CURDATE()) OR '2016-08-11' BETWEEN from_date AND COALESCE(to_date,CURDATE())")