【问题标题】:How to get the last record with a condition in Django如何在 Django 中获取带有条件的最后一条记录
【发布时间】:2023-01-17 20:19:21
【问题描述】:

我正在尝试在 Django 中获取表的最后一条记录。

型号:房间

id room staff_id
1 103 1000
2 105 1000
3 107 1555

工作人员(编号1000)有两条记录,但我只想获得他的最后一条记录。

getStaffRecords = Rooms.objects.get(staff_id=1000)
staffRoom = getStaffRecords.room

在这里我得到一个错误,因为我有不止一条记录。 错误:get() 返回了多个房间——它返回了 2 个!

有人有解决办法吗?

我尝试使用这样的方法:

getStaffRecords = Rooms.objects.get(staff_id=1000).last()
staffRoom = getStaffRecords.room

但它没有用,因为在这种情况下,“get”不被 Django 识别。

【问题讨论】:

    标签: django database sqlite django-models django-views


    【解决方案1】:

    尝试:

    Rooms.objects.filter(staff_id=1000).last()
    

    那是因为您不能在单个对象中使用 last()get() 函数返回单个对象。

    【讨论】:

    • 它的工作!伟大的。我不知道哪种类型的对象返回 get 和 filter。谢谢。
    猜你喜欢
    • 2012-01-23
    • 2023-03-16
    • 2011-10-21
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多