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

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

问题描述

我有两个问题,但它们与相同的主题有关。

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

我知道如何从中获取数据循环使用模板标签

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循环。

我得到: / p>

I get:

'Status' object is not iterable

我的问题是:


  1. 如何从给定模型的数据库获取最新条目?

  2. 如何设置我的模板标签只允许单个记录?


推荐答案

这里有两个不同的问题:

You have two different questions here:


  1. 如何从数据库中检索最新的对象。 / li>
  1. How do I retrieve the latest object from the database.

您可以使用 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天全站免登陆