python - Django - 获取创建的最后一个对象,同时过滤器

标签 python django filter django-views

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

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

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

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

其次,是否可以同时创建过滤器或组合列表?这是一个例子:

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

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

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

正确的语法是什么?

最佳答案

我还没有尝试过,但我会看看 latest() QuerySets 上的运算符(operator):

latest(field_name=None)

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

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

Entry.objects.latest('pub_date')

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.

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

Note latest() exists purely for convenience and readability.

还有 model docs on get_latest_by :

get_latest_by

Options.get_latest_by

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

Example:

get_latest_by = "order_date"

See the docs for latest() for more.

编辑:Wade 对 Q() 运算符有很好的回答。

关于python - Django - 获取创建的最后一个对象,同时过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1256190/

相关文章:

python - 在 python 中使用继承

excel - 自动筛选日期错误 : "Method of Range Class Failed"

reactjs - HTTP方法的错误: 401 (Unauthorized) on React & Django(DRF)

python - Django 管理员保存错误 : get_db_prep_value() got an unexpected keyword argument 'connection'

javascript - 仅遍历一次时将可变数量的过滤条件应用于 javascript 数组?

elasticsearch - 在ES中,如何编写映射,以便对小写和大写字母都使用通配符查询?

python - 在 Python 3 中解码二维码

python - 使用 pandas,如何重新采样并应用函数来添加列?

python - 提交行时Django外键约束错误

python - 如何向 Django 页面添加延迟重定向?