什么是SQL查询的Django语法包括内连接,count,在哪里?

时间:2017-05-23 14:46:59

标签: sql-server django python-3.x

我有一个DB,其中包含如下表格:

class Maindata(models.Model):
    index = models.TextField(primary_key=True)
    dco = models.IntegerField(db_column='DCO', blank=True, null=True)
    patient = models.IntegerField(db_column='PATIENT', blank=True, null=True)
    primary = models.IntegerField(db_column='PRIMARY', blank=True, null=True)
    fsdate = models.TextField(db_column='FSDATE', blank=True, null=True)
    uhpi = models.TextField(db_column='UHPI', blank=True, null=True)
    uhpiold = models.TextField(db_column='UHPIold', blank=True, null=True)
    wghnum = models.TextField(db_column='WGHNUM', blank=True, null=True)
    idstatus = models.TextField(db_column='IDstatus', blank=True, null=True)
    fsc2date = models.TextField(db_column='FSC2DATE', blank=True, null=True)
    iopat = models.TextField(db_column='IOPAT', blank=True, null=True)
    anndate = models.TextField(db_column='ANNDATE', blank=True, null=True)
    site =  models.ForeignKey('Sitelut', db_column='SITE', to_field='code', blank=True, null=True, related_name='site')

和化疗表:

   class Chemotherapy(models.Model):
    index = models.TextField(primary_key=True)
    patient = models.IntegerField(db_column='PATIENT', blank=True, null=True)
    primary = models.IntegerField(db_column='PRIMARY', blank=True, null=True)
    episode = models.IntegerField(db_column='EPISODE', blank=True, null=True)
    material = models.ForeignKey('Chemomateriallut', db_column='MATERIAL', blank=True, null=True, related_name='material')
    stdate = models.TextField(db_column='STDATE', blank=True, null=True)
    enddate = models.TextField(db_column='ENDDATE', blank=True, null=True)
    method = models.ForeignKey('Chemomethodlut', db_column='METHOD', blank=True, null=True, related_name='method')

我正在尝试执行连接两个表并获取一些信息的查询(以下是我的查询):

Select count(*), Chemotherapy.Material, Chemotherapy.METHOD from 
Chemotherapy inner join Maindata on Chemotherapy.Patient = Maindata.Patient and Chemotherapy.[Primary] = Maindata.[Primary] where ((Maindata.site) = '1749')
group by Chemotherapy.MATERIAL, Chemotherapy.METHOD

最初,我使用过滤器和注释。但是,我意识到它没有返回相同的结果(因为我没有检查它是否具有相同的主ID)。

我的初始语法如下:

Chemotherapy.objects.filter(
    patient__in=Maindata.objects.filter(site='1749')
.values('patient').distinct()).select_related().values('material', 'method')
.annotate(dcount=Count('material', 'method'))

如何修复此查询?

1 个答案:

答案 0 :(得分:0)

如果您的SQL查询按预期工作,您可以使用Django ORM原始SQL选项:

query = "Select count(*), Chemotherapy.Material, Chemotherapy.METHOD from ..."
Chemotherapy.objects.raw(query)