我正在try 使用此模型过滤博客帖子:

class Post(models.Model):
    is_podcast = models.BooleanField(default=False)
    category = models.ManyToManyField(Category)
    title = models.CharField(max_length=500)
    slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True)
    body = RichTextUploadingField()
    likes_count = models.IntegerField(default=0 , help_text="amount of likes")
    vip_members_only = models.BooleanField(default=False)

    def __str__(self):
        return self.title

我正在使用这个视图来过滤帖子:

def Index_view(request , slug=None):
    posts = Post.objects.filter()
    kind = request.GET.get('type')
    order = request.GET.get('order')
    author = request.GET.get('author')
    search = request.GET.get('search')

    if slug:
        cat = get_object_or_404(Category , slug=slug)
        posts.filter(category = cat)

    if search != '' and search is not None:
        posts.filter(Q(title__icontains = search))

    if kind != '' and kind is not None:
        if kind == 'podcast':
            posts.filter(is_podcast=True)
        if kind == 'all':
            pass
        if kind == 'post':
            posts.filter(is_podcast=False)  

    con = {'posts' : posts}
    return render(request , 'Weblog/posts.html' , con)

以下也是前urls.py名:

path('posts/', Index_view),
re_path(r'^posts/(?P<slug>[\w-]+)/$', Index_view),

当我使用这个URL(http://127.0.0.1:8000/blog/posts/some-slug/?search=test)时,我收到了所有的帖子,过滤不起作用.有什么问题吗?

推荐答案

您缺少"覆盖"posts变量的能力.

def Index_view(request , slug=None):
    posts = Post.objects.all()
    kind = request.GET.get('type')
    order = request.GET.get('order')
    author = request.GET.get('author')
    search = request.GET.get('search')

    if slug:
        cat = get_object_or_404(Category , slug=slug)
        posts = posts.filter(category = cat)

    if search != '' and search is not None:
        posts = posts.filter(Q(title__icontains = search))

    if kind != '' and kind is not None:
        if kind == 'podcast':
            posts = posts.filter(is_podcast=True)
        #if kind == 'all':  --> useless
        #    pass
        if kind == 'post':
            posts = posts.filter(is_podcast=False)  

    con = {'posts' : posts}
    return render(request , 'Weblog/posts.html' , con)

Python相关问答推荐

遵循轮廓中对象方向的计算线

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

如何使用Python中的clinicalTrials.gov API获取完整结果?

如何使用SubProcess/Shell从Python脚本中调用具有几个带有html标签的参数的Perl脚本?

比较两个二元组列表,NP.isin

对Numpy函数进行载体化

比较两个数据帧并并排附加结果(获取性能警告)

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

如何从具有不同len的列表字典中创建摘要表?

计算组中唯一值的数量

移动条情节旁边的半小提琴情节在海运

Pandas Loc Select 到NaN和值列表

如何并行化/加速并行numba代码?

使用groupby方法移除公共子字符串

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

如何求相邻对序列中元素 Select 的最小代价

GPT python SDK引入了大量开销/错误超时

如何强制向量中的特定元素在Gekko中处于优化解决方案中

如何写一个polars birame到DuckDB