Django model latest() method

2019-06-19 11:02发布

I am having the following issue (BTW I think I had not had this problem the day before):

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

AttributeError: 'Rule' object has no attribute 'latest'

Why am I getting the error?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-19 11:21

latest method belongs to QuerySet, not model.

Replace following line:

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

with:

rule = Rule.objects.filter(user=user).latest('id')
查看更多
\"骚年 ilove
3楼-- · 2019-06-19 11:37

The get() function of the Model Manager returns an instance of the Model itself.

The latest() function you mention belongs to the QuerySet class. Calling .filter(), .all(), .exclude() etc, all return a QuerySet.

What you're likely looking for is to first filter for the specific user, then get the latest result by 'id':

rule = Rule.objects.filter(user=user).latest('id')

See here for the docs on querying models

查看更多
登录 后发表回答