Django - 获取创建的最后一个对象,同时过滤器 [英] Django - Getting last object created, simultaneous filters

查看:21
本文介绍了Django - 获取创建的最后一个对象,同时过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我对 Django 和 Python 完全陌生.

Apologies, I am completely new to Django and Python.

我有两个问题.首先,我将如何获取对象列表中创建的最后一个对象(或最高 pk)?例如,我知道我可以使用以下内容来获取第一个对象:

I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object:

list = List.objects.all()[0]

有没有办法获取List.objects的长度?我试过 List.objects.length 但无济于事.

Is there a way to get the length of List.objects? I've tried List.objects.length but to no avail.

第二,是否可以同时创建过滤器或组合列表?下面是一个例子:

Second, is it possible to create simultaneous filters or combine lists? Here is an example:

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number)

我想要类似上面的东西,但更像:

I want something like the above, but more like:

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number or home_phone=number)

如果有的话,正确的语法是什么?

What is the correct syntax, if any?

推荐答案

我还没试过,但我会看看 latest() 运算符在 查询集:

I haven't tried this yet, but I'd look at the latest() operator on QuerySets:

最新的(field_name=None)

latest(field_name=None)

返回最新的对象表,按日期,使用 field_name作为日期字段提供.

Returns the latest object in the table, by date, using the field_name provided as the date field.

这个例子返回最新的Entry在表中,根据pub_date 字段:

This example returns the latest Entry in the table, according to the pub_date field:

Entry.objects.latest('pub_date')

Entry.objects.latest('pub_date')

如果您的模型的 Meta 指定get_latest_by,你可以不使用给latest() 的field_name 参数.Django 将使用中指定的字段默认为 get_latest_by.

If your model's Meta specifies get_latest_by, you can leave off the field_name argument to latest(). Django will use the field specified in get_latest_by by default.

像 get(), latest() 引发如果对象不存在,则DoesNotExist以给定的参数存在.

Like get(), latest() raises DoesNotExist if an object doesn't exist with the given parameters.

注意 latest() 纯粹是为了便利性和可读性.

Note latest() exists purely for convenience and readability.

以及关于 get_latest_by 的 模型文档:

And the model docs on get_latest_by:

get_latest_by

get_latest_by

Options.get_latest_by

Options.get_latest_by

模型中 DateField 或 DateTimeField 的名称.这指定了在模型 Manager 的最新方法中使用的默认字段.

The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager's latest method.

示例:

get_latest_by = "order_date"

get_latest_by = "order_date"

有关更多信息,请参阅 latest() 的文档.

See the docs for latest() for more.

Wade 对 Q() 运算符有很好的回答.

Wade has a good answer on Q() operator.

这篇关于Django - 获取创建的最后一个对象,同时过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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