django - django-objects 标签过滤器
问题描述
我在我的 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 post in posts.object_list|lasted %} 并将其 in 过滤器排序为按排序(或排序)与键参数的列表(键是比较 post_date 的函数)。或者尝试在不使用自定义过滤器的情况下传递给 Paginator 排序查询集 Paginator(post_list.order_by('...'),18) – Александр 18 小时
推荐阅读
- django - 我应该为爬行/抓取部分制作一个单独的 django 项目吗?
- reactjs - Webpack 5 bundle.js 不包含所有 src 内容
- django - 是否可以有一个外键引用 Django 中的多个类?
- javascript - 未捕获的参考错误:未定义绘制 - 请帮助我
- python - 无法相应提交 Django 表单
- javascript - 如何检查两个对象的相等性,一个对象的属性类型是数字,其他类型是字符串,但它们是数字
- php - 在制作 ENUM 字段时,我是否应该在整数前添加 '
- javascript - Java 脚本按键事件
- reactjs - react-router-dom `history`:无法读取未定义的属性“推送”
- c++ - 如何用空格分隔行以存储用户地址