我正在html页面上调用post.objects.all对象。在同一页上的最后一个帖子。我为此做了一个过滤器,但出现错误。调用我想做的最后3个帖子
我无法输入.objects.order_by(),因为它可能是一个对象。
我无法输入.objects.order_by(),因为它可能是一个对象。
views.py :
def post_index(request):
post_list = Post.objects.all()
category = Category.objects.all()
query = request.GET.get('q')
if query:
post_list = post_list.filter(
Q(post_title__icontains=query) |
Q(post_content__icontains=query) |
Q(post_date__date=query)
).distinct()
paginator = Paginator(post_list, 18) # Show 5 contacts per page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
context = {
'posts': posts,
'category':category,
}
return render(request, "post/post-list.html", context)
html:
{%for post in posts|lasted %}
filter.py
@register.filter
def lasted(post):
return post.objects.order_by('post_date')[:3]
AttributeError at /post/index/
'Page' object has no attribute 'objects'
Request Method: GET
Request URL: http://127.0.0.1:8000/post/index/
Django Version: 2.2.7
Exception Type: AttributeError
Exception Value:
'Page' object has no attribute 'objects'
Exception Location: C:\Users\Barbaros\Desktop\All\env\lib\site-packages\django\template\defaultfilters.py in lasted, line 73
Python Executable: C:\Users\Barbaros\Desktop\All\env\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['C:\\Users\\Barbaros\\Desktop\\All',
'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts\\python37.zip',
'C:\\Users\\Barbaros\\Desktop\\All\\env\\DLLs',
'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib',
'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts',
'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\Lib',
'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\DLLs',
'C:\\Users\\Barbaros\\Desktop\\All\\env',
'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib\\site-packages']
Server time: Fri, 22 Nov 2019 20:36:41 +0000
我以为您在昨天的评论后更改了问题中的代码。现在尝试{%for posts.object_list | lasted%},并按sort(或sorted)与key参数(key为func进行比较post_date)将其在过滤器中作为列表排序。或者尝试不使用自定义过滤器而传递给Paginator排序的查询集Paginator(post_list.order_by('...'),18),然后–Александр18小时