如何使用Django ORM编写此Group By查询?

时间:2017-07-07 21:17:46

标签: python django django-models

我正在尝试将此SQL转换为ORM Django:

SELECT * FROM DOCUMENTO D WHERE D.PASTA_ID = 4 AND D.PAI_ID = 10 AND D.VERSAO = (SELECT MAX(VERSAO) FROM DOCUMENTO E WHERE D.ID_DOC = E.ID_DOC GROUP BY ID_DOC)

我尝试使用注释但不起作用。有人可以帮帮我吗?

模型

class Documento(models.Model):
    pasta = models.ForeignKey(u'Pasta')
    pai = models.ForeignKey(u'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='doc_pai')
    nome = models.CharField(u'Nome', max_length=255)
    versao = models.IntegerField(u'Versao', default=1)
    id_doc = models.IntegerField(u'ID Documento', null=True)

0 个答案:

没有答案