抱歉,我对 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/