2

我需要在 Django 的查询中加入 3 个表。

我在 MySQL 中有两个查询,都返回相同的结果,使用一个或另一个查询并不重要:

在哪里查询

SELECT dv.Division,
    COUNT(or.`ct_id`) AS `orders`,
    COUNT(CASE WHEN gr.`Status` = 'on going' THEN 1 ELSE NULL END) AS `ge_on_going`,
FROM order or, zone zo, cctt ct, division dv
WHERE or.zone_id = zo.id
AND or.cctt_id = ct.id
AND zo.division_id = dv.id
GROUP BY dv.Division

使用连接查询

SELECT dv.Division,
COUNT(or.`ct_id`) AS `orders`,
COUNT(CASE WHEN gr.`Status` = 'on going' THEN 1 ELSE NULL END) AS `ge_on_going`,
FROM order or
    INNER JOIN cctt ct ON (or.cctt_id = ct.id)
    INNER JOIN zone zo ON (or.zone_id = zo.id)
    INNER JOIN division dv ON (zo.division_id = dv.id)
GROUP BY dv.Division

该查询如何翻译为 django,我有这个,但它不起作用:

楷模

class DivisionModel(models.Model):
    id = models.PositiveIntegerField(db_column='Id', primary_key=True)
    division = models.CharField(db_column='Division', max_length=50)
    
class ZoneModel(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    zone = models.CharField(db_column='Zone', max_length=50)
    division = models.ForeignKey(DivisionModel, on_delete=models.DO_NOTHING, db_column='Division_id')

class OrderModel(models.Model):
    zone = models.ForeignKey(ZonaModel, on_delete=models.DO_NOTHING, db_column='Zone_Id')
    cctt = models.ForeignKey(CCTTModel, on_delete=models.DO_NOTHING, db_column='CCTT_Id')
    fservice = models.DateTimeField(db_column='FServicio')

class CCTTModel(models.Model):
    status = models.CharField(db_column='Status', max_length=23)
4

1 回答 1

1

你可以这样尝试annotation

from django.db.model import Q, Count

DivisionModel.objects.values('division').annotate(orders=Count('zonemodel__ordermodel__cctt'),  ge_on_going=Count('zonemodel__ordermodel__cctt', filter=Q(zonemodel__ordermodel__cctt__status="on going"))).values('division', 'order', 'ge_on_goin')
于 2020-08-04T11:15:40.290 回答