Primary key requirement in raw SQL complicates the query in Django

后端 未结 4 962
醉酒成梦
醉酒成梦 2021-01-05 16:52

To get max value from a simple table of values, I can write the following query in Django:

MyTable.objects.aggregate(Max(\'value\'))

The SQ

4条回答
  •  攒了一身酷
    2021-01-05 17:43

    I just had same issue, @Tinashe Robert's not working for me. May I share my solution(Python 3.7.7, Django 3.0.5):

    PS: Yes, @catavaran's answer is native Python, but if one really want to use RAW?

    • Firstly, primary_key needs to be appointed to one column in MySQL DB field, i.e.:
     class MyTable(model.Model):
         id = models.AutoField(primary_key=True)
         value = models.IntegerField(10)
         ... 
    

    with API shell:

    >>> MyTable.objects.raw('SELECT id, max(value) as mx from MyTable')[0].mx
    

    or simpler solution:

    >>> from django.db.models import Max
    >>> MyTable.objects.all().aggregate(Max('value'))
    

提交回复
热议问题