Django model latest() method

穿精又带淫゛_ 提交于 2019-12-10 13:23:37

问题


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?


回答1:


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




回答2:


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')


来源:https://stackoverflow.com/questions/21077865/django-model-latest-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!