Django 从数据库中获取最新条目 [英] Django Get Latest Entry from Database

查看:42
本文介绍了Django 从数据库中获取最新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个问题,但它们与同一主题相关.

I've got 2 questions, but they are related to the same topic.

我知道如何使用模板标签从 for 循环 中检索数据

I know how to retrieve data from a for loop using template tags

{% for status in status %}

    <tr>
        <td>{{ status.status}}</td>
    </tr>

{% endfor %}

然而,当我想检索单个对象时,即使我使用:

However when I want to retrieve a single object i get an error even when i use:

po = Status.objects.latest('id')

并删除 for 循环.

and remove the for loop.

我明白了:

'Status' object is not iterable

我的问题是:

  1. 如何从数据库中获取给定模型的最新条目?
  2. 如何设置我的模板标签以只允许一条记录?

推荐答案

您在这里有两个不同的问题:

You have two different questions here:

  1. 如何从数据库中检索最新的对象.

您可以使用 latest() 查询集运算符.通过阅读文档,您会注意到该运算符适用于日期字段,而不是整数.

You can do this using the latest() queryset operator. By reading the docs you will note that this operator works on date fields, not integers.

Status.objects.latest('date_added') # or date_updated

如果您想根据 ID 执行此操作,则需要按 ID 排序并选择第一个结果.(这仅在您使用递增主键时有效,它不适用于 UUID 或随机生成的哈希).

If you want to do this off the ID you will need to order by ID and select the first result. (this will only work if you are using incrementing primary keys, it will not work with UUID's or randomly generated hashes).

Status.objects.order_by('id')[0]

旁注:我个人会使用 date_ added/date_updated 方式来做到这一点.

Side note: I would personally use the date_added / date_updated way of doing this.

  1. 迭代单个对象

不能迭代单个对象.为此,您需要使用不同的模板.或者,您需要将单个对象添加到列表中.

A single object cannot be iterated over. For this you will need to use a different template. Or, you will need to add the single object into a list.

# note the [] around the query
result = [Status.object.latest('date_added')]

我个人对列出单个/多个结果有不同的看法.我有一个用于许多结果对象的 ListView 和一个用于单个对象的 DetailView.

Personally I have a different views for listing single / multiple result. I have a ListView for many result objects and a DetailView for single objects.

这篇关于Django 从数据库中获取最新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆