如何在 Django orm 中执行子查询?
Posted
技术标签:
【中文标题】如何在 Django orm 中执行子查询?【英文标题】:how to execute subquery in Django orm? 【发布时间】:2014-11-17 13:51:34 【问题描述】:django 模型.py
class cdr(models.Model):
id = models.AutoField(primary_key=True, unique=True, verbose_name='id',)
disposition = models.CharField(max_length=45, default='')
did = models.CharField(max_length=50, default='')
def __unicode__(self):
return u'%s' % self.id
class Meta:
ordering=['-calldate']
db_table = 'cdr'
mysql 查询:
select id, did as diddst, count(did) as count, (select count(did) from cdr where disposition='NO ANSWER' and did=diddst) as countnoanswer from cdr where did in (79244576674, 79244576619) group by did;
结果
+------+-------------+-------+---------------+
| id | diddst | count | countnoanswer |
+------+-------------+-------+---------------+
| 1011 | 79244576619 | 218 | 71 |
| 1756 | 79244576674 | 1528 | 654 |
+------+-------------+-------+---------------+
如何在 Django orm 中执行这个子查询?帮帮我,请 Django 伙计们!
【问题讨论】:
【参考方案1】:您必须进行原始查询。
cdr.objects.raw('...')
【讨论】:
以上是关于如何在 Django orm 中执行子查询?的主要内容,如果未能解决你的问题,请参考以下文章
在 django ORM 中查询时如何将 char 转换为整数?