Django模型latest()方法

jaz*_*lue 6 python django django-models django-queryset

我有以下问题(BTW我想我前一天没遇到过这个问题):

>>> rule = Rule.objects.get(user=user)
>>> rule.id
1
>>> rule = Rule.objects.get(user=user).latest('id')

AttributeError: 'Rule' object has no attribute 'latest'
Run Code Online (Sandbox Code Playgroud)

为什么我收到错误?

Dwi*_*ing 8

模型管理器的get()函数返回对象本身的实例.

您提到的latest()函数属于QuerySet类.调用.filter(),. all(),. exclude()等都返回一个查询集.

你可能想要的是首先过滤特定用户,然后通过'id'获得最新结果:

rule = Rule.objects.filter(user=user).latest('id')
Run Code Online (Sandbox Code Playgroud)

请参阅此处查看有关查询模型的文档