【问题标题】:How to get last added id from table in djagno?如何从 django 的表中获取最后添加的 id?
【发布时间】:2021-08-29 05:45:32
【问题描述】:

我想获取我使用的最后一个 id

count_id = staff.objects.latest('id')

但它显示的值是(条目总数为3)

staff object (3)

我只想要 3 个

【问题讨论】:

  • 在末尾加上.id 以获得您想要的字段?

标签: django django-models django-views django-templates


【解决方案1】:

查找最后一个对象有 3 种方法:

1-

Staff.objects.last()  #if not change default sort 

2-

Staff.objects.order_by("id").last() #always True

3-

Staff.objects.order_by("-id").first() #always True

从模型中获取 id 有两种主要方式

1- 只需从数据库中选择 id

选择 id 并在字典模板中返回

Staff.objects.order_by("id").values("id").last() # output: {"id":3}

选择 id 并在元组模板列表中返回

Staff.objects.order_by("id").values_list("id").last() # output: (86,)

选择 id 并在列表模板中返回

Staff.objects.order_by("id").values_list("id", flat=True).last() # output: 86

2- 选择所有字段并查看一个

Staff.objects.order_by("id").last().id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 2013-01-27
    • 2019-04-21
    • 2014-01-20
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多