Primary key requirement in raw SQL complicates the query in Django

后端 未结 4 963
醉酒成梦
醉酒成梦 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:36

    U can use

    ModelName.objects.raw('SELECT 1 as id , max(value) FROM mytable')
    
    0 讨论(0)
  • 2021-01-05 17:39

    You should use custom SQL instead of Manager.raw() method:

    from django.db import connection
    
    cursor = connection.cursor()
    cursor.execute('SELECT max(value) FROM mytable')
    max_value = cursor.fetchone()[0]
    
    0 讨论(0)
  • 2021-01-05 17:40

    I would do something like:

    select id, value from mytable order by value desc limit 1
    
    0 讨论(0)
  • 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'))
    
    0 讨论(0)
提交回复
热议问题