You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:如何按作者过滤并展示其文章关联的分类

问题分析与解决方案

原代码中Category.objects.filter(post_author=username)会报错,因为Category模型并没有post_author字段。关联关系是Post通过exercisename外键指向Category,同时Post有author字段关联用户,所以要获取某作者发布文章对应的分类,需要通过反向关联查询。

正确的查询方式

有两种常见实现方式:

方式1:通过Post反向关联查询Category

利用Django的反向关联(默认反向关联名为post_set),直接过滤关联到目标用户文章的分类:

def userpost(request, username):
    # 获取目标用户对象
    user = User.objects.get(username=username)
    # 查询该用户所有文章对应的分类,用distinct()去重避免重复
    categories = Category.objects.filter(post__author=user).distinct()
    context = { 
        'categories': categories,
    }
    return render(request, 'blog/user_Posts.html', context) 

方式2:先获取用户文章,再提取分类

如果需要同时展示用户的文章和对应分类,可先查询文章再提取分类:

def userpost(request, username):
    user = User.objects.get(username=username)
    # 获取用户所有文章,用select_related预加载分类减少数据库查询次数
    posts = Post.objects.filter(author=user).select_related('exercisename')
    # 从文章集合中提取不重复的分类
    categories = set(post.exercisename for post in posts)
    context = { 
        'posts': posts,
        'categories': categories,
    }
    return render(request, 'blog/user_Posts.html', context) 

补充优化

如果想让反向关联语义更清晰,可以在Post的外键字段中自定义related_name:

exercisename = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='posts')

之后查询可改为Category.objects.filter(posts__author=user).distinct(),可读性更强。

内容的提问来源于stack exchange,提问作者lahef37460

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:33:36