SQL查询逻辑到Django ORM查询逻辑

时间:2019-01-04 21:18:54

标签: sql django orm

我试图考虑如何将以下SQL查询构造为Django ORM查询,但是我的多次尝试都没有运气。有人可以帮忙吗?

SELECT targets_genetarget.gene, count(targets_targetprediction.gene) as total FROM targets_genetarget LEFT OUTER JOIN targets_targetprediction on targets_targetprediction.gene = targets_genetarget.gene WHERE list_name LIKE %s GROUP BY targets_genetarget.gene

class GeneTarget(models.Model):
    list_name = models.CharField(max_length=100)
    gene = models.CharField(max_length=50)
    date_added = models.DateField(auto_now=True)

    class Meta:
        unique_together = (('list_name', 'gene'),)

    def __str__(self):
        return self.list_name


class TargetPrediction(models.Model):
    specimen_id = models.CharField(max_length=100)
    patient_peptide = models.ForeignKey(Peptide, on_delete=models.CASCADE, verbose_name="Peptide", related_name="predictions")
    allele = models.ForeignKey(Allele, on_delete=models.CASCADE, verbose_name="Allele", related_name="predictions")
    gene = models.CharField(max_length=50)

    class Meta:
        unique_together = (('specimen_id', 'patient_peptide', 'allele', 'gene'),)

    def get_absolute_url(self):
        return f'/samples/specid-{self.specimen_id}'

    def __str__(self):
        return (f'Specimen: {self.specimen_id} Peptide: {self.patient_peptide} Allele: {self.allele} Gene: {self.gene} ')

1 个答案:

答案 0 :(得分:0)

没有什么可阻止您使用TargetPrediction.gene属性将to_field字段声明为外键的,因此您根本不需要更改数据:

class TargetPrediction(models.Model):
    ...
    gene = models.ForeignKey("GeneTarget",  to_field="gene")

现在您的查询就变成:

GeneTarget.objects.filter(list_name="whatever").values("gene").annotate(total=Count("targetprediction"))