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

Field 'id' expected a number but got <taggit.managers._TaggableManager object

我正在构建一个 BlogApp,但遇到错误。

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

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

Field 'id' expected a number but got <taggit.managers._TaggableManager object at 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())

但它显示此错误

The QuerySet value for an exact lookup must be limited to one result using slicing.

如有任何帮助,我们将不胜感激。

提前致谢。

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

失败并出现错误:

The QuerySet value for an exact lookup must be limited to one result using slicing.

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

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

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

If user_1 have set two interests then this code is showing users if one of tags have similar to other users, BUT i am trying to show if more than 2 tags are similar then show users.

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

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