Django使用taggit过滤同兴趣标签用户报id类型错误如何解决?
问题原因
- 第一次报错是因为你直接将
interests这个TaggableManager管理器对象传入过滤条件,ORM期望接收标签ID、标签实例类可序列化值,而非管理器对象。 - 第二次报错是因为你将多结果的标签查询集传给了
=精确匹配条件,=后面只能跟随单个值,不能传入包含多个结果的查询集。
解决方案
直接使用taggit支持的__in反向查询语法,匹配持有任意相同兴趣标签的用户即可,基础实现代码如下:
def test_hobbiesss(request, user_id): # 获取当前用户的所有兴趣标签 current_user_interests = request.user.profile.interests.all() # 过滤持有任意相同标签的用户,排除当前用户自身并去重 users = Profile.objects.filter(interests__in=current_user_interests)\ .exclude(id=request.user.profile.id)\ .distinct() context = {'users': users} return render(request, 'list.html', context)
如果需要按兴趣重合度排序(匹配标签越多排序越靠前),可以使用聚合统计优化:
from django.db.models import Count def test_hobbiesss(request, user_id): current_user_interests = request.user.profile.interests.all() users = Profile.objects.filter(interests__in=current_user_interests)\ .exclude(id=request.user.profile.id)\ # 统计匹配的标签数量 .annotate(matched_tags_count=Count('interests'))\ # 按匹配数量倒序排列 .order_by('-matched_tags_count')\ .distinct() context = {'users': users} return render(request, 'list.html', context)
实现说明
interests__in参数可以传入标签查询集,自动匹配所有持有任意对应标签的Profile记录distinct()用于避免同一个用户匹配到多个标签时返回重复结果exclude规则用于过滤掉当前用户自身,不需要出现在相似用户列表中- 聚合排序版本可以优先推荐兴趣重合度更高的用户,更符合推荐场景需求
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

