首页 > 解决方案 > 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 

标签: djangoobjectfilter

解决方案


我以为您在昨天发表评论后更改了问题中的代码。现在尝试 {%for post in posts.object_list|lasted %} 并将其 in 过滤器排序为按排序(或排序)与键参数的列表(键是比较 post_date 的函数)。或者尝试在不使用自定义过滤器的情况下传递给 Paginator 排序查询集 Paginator(post_list.order_by('...'),18) – Александр 18 小时


推荐阅读