0

I'm trying to convert this SQL into 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)

I've tried to use annotate but doesn't work. Someone can help me?

models

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)
FamousJameous
  • 1,565
  • 11
  • 25
  • Have you looked at this: https://stackoverflow.com/a/629691/3901060 ? – FamousJameous Jul 07 '17 at 21:29
  • Yes, I've tried but I can't get even close to the query I've mentioned – Rafael Pinheiro Jul 12 '17 at 13:35
  • Yeah, I didn't notice the nested query part before. If all else fails, you can use raw SQL in Django: https://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries – FamousJameous Jul 12 '17 at 19:46
  • First, I would like to thank for your help @FamousJameous . Thank you! With raw sql I can get the result I want. But next I have many Q objects that only can be used as filter in queryset objects. – Rafael Pinheiro Jul 14 '17 at 18:28

0 Answers0