Django select max id

前端 未结 6 2029
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 03:39

given a standard model (called Image) with an autoset \'id\', how do I get the max id?

So far I\'ve tried:

max_id = Image.objects.all().aggregate(Max         


        
相关标签:
6条回答
  • 2020-12-29 03:56

    Latest object without catching exception and using django orm:

    Image.objects.filter().order_by('id').first()

    0 讨论(0)
  • 2020-12-29 03:58

    Your logic is right, this will return the max id

    res = Image.objects.filter().aggregate(max_id=Max('pk'))
    res.get('max_id')
    
    0 讨论(0)
  • 2020-12-29 04:13

    this also work perfectly:

    max_id = Image.objects.values('id').order_by('-id').first()
    
    0 讨论(0)
  • 2020-12-29 04:16

    In current version of django (1.4) it is even more readable

    Image.objects.latest('id').id

    0 讨论(0)
  • 2020-12-29 04:17

    I know this already has a right answer but here it's another way of doing it:

    prev = Image.objects.last()
    

    This gives you the last object.

    0 讨论(0)
  • 2020-12-29 04:21

    Just order by reverse id, and take the top one.

    Image.objects.all().order_by("-id")[0]
    
    0 讨论(0)
提交回复
热议问题