字段 'id' 需要一个数字,但得到 <taggit.managers._TaggableManager 对象

时间:2021-07-27 06:14:08

标签: python django django-models django-views tags

我正在构建一个博客应用程序,但遇到错误。

我想要做什么:-(我想要它做什么)

我正在过滤具有相似 tags 的用户。但是当我尝试过滤时,错误一直显示 -

<块引用>

字段 'id' 需要一个数字,但在 0x0000015B266D3288> 处得到

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    interests = TaggableManager(verbose_name='interests')

views.py

def test_hobbiesss(request,user_id):

    users = Profile.objects.filter(interests=request.user.profile.interests)

    context = {'users':users}
    return render(request, 'list.html', context)

我尝试了什么:-

  • 我也试过
    users = Profile.objects.filter(interests=request.user.profile.interests.all())

但它显示此错误

<块引用>

精确查找的 QuerySet 值必须使用切片限制为一个结果。

任何帮助将不胜感激。

提前致谢。

1 个答案:

答案 0 :(得分:0)

users = Profile.objects.filter(interests=request.user.profile.interests.all())

失败并出现错误:

<块引用>

精确查找的 QuerySet 值必须使用切片限制为一个结果。

因为,您是直接在 interests 中进行搜索,这是一种精确查找。因为,用户的兴趣可能有多个,您需要 __in 查找:

users = Profile.objects.filter(interests__in=request.user.profile.interests.all())

请注意,这也将获得 request.user 的配置文件,因此如果您需要排除它,您可以附加 .exclude(user=request.user)

<块引用>

如果 user_1 设置了两个兴趣,那么此代码会向用户显示其中一个标签是否与其他用户相似,但我试图显示是否有 2 个以上的标签相似,然后向用户显示。

在这种情况下,您可以对兴趣annotate使用filter

users = (
    Profile.objects.filter(
        interests__in=request.user.profile.interests.all(),
    ).annotate(
        interests_cnt=Count('interests'),
    ).filter(
        interests_cnt__gt=1,
    )
)