Django - 创建最后一个对象,同时进行过滤 [英] Django - Getting last object created, simultaneous filters
问题描述
我有2个问题。首先,如何在对象列表中创建最后一个对象(或最高的pk)?例如,我知道我可以使用以下内容来获取第一个对象:
list = List.objects.all() [0]
有没有办法获取List.objects的长度?我试过List.objects.length,但没有用。
其次,是否可以创建同时过滤器或组合列表?这是一个例子:
def findNumber(request,number)
phone_list = Numbers.objects.filter(cell =数字)
我想要像上面这样的东西,但更像:
def findNumber(request,number)
phone_list = Numbers.objects.filter(cell = number或home_phone = number)
什么是正确的语法(如果有)?
我还没有尝试过,但是我会在 latest()运算符dev / ref / models / querysets /#ref-models-querysetsrel =noreferrer> QuerySets :
最新(field_name = None)
返回
表中的最新对象,按日期,使用作为日期字段提供的field_name
。 p>
根据
pub_date字段,此示例返回表中最新的Entry
:
Entry.objects.latest('pub_date')
如果您的模型的Meta指定
get_latest_by,您可以将
field_name参数留给latest()。
Django将默认使用
get_latest_by中指定的字段。
喜欢get(),latest()引发
DoesNotExist如果对象不具有给定参数的
。
注意最近()存在纯粹为
方便和可读性。
而且 get_latest_by 上的模型文档:
get_latest_by
选项。 get_latest_by
模型中DateField或DateTimeField的名称。这指定了您的模型管理器最新方法中使用的默认字段。
示例:
get_latest_by =order_date
有关更多信息,请参阅最新()文档。
编辑:Wade在Q()运算符上有一个很好的答案。
Apologies, I am completely new to Django and Python.
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]
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?
I haven't tried this yet, but I'd look at the latest() operator on QuerySets:
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.
And the 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.
Edit: Wade has a good answer on Q() operator.
这篇关于Django - 创建最后一个对象,同时进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!