【问题标题】:Field 'id' expected a number but got <taggit.managers._TaggableManager object字段 'id' 需要一个数字,但得到 <taggit.managers._TaggableManager 对象
【发布时间】:2021-07-27 06:14:08
【问题描述】:

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

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

我正在过滤具有相似 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 值必须使用切片限制为一个结果。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

  • 你是在尝试获取与登录用户有相同兴趣的用户吗?
  • 是的,先生,我正在按照您所说的进行尝试
  • 在这种情况下,请更新您的问题以反映它,因为这提供了更多上下文。

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


【解决方案1】:
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,
    )
)

【讨论】:

  • 非常感谢,它成功了,而且我还使用.distinct() 排除重复结果。但是,如果我想向拥有超过 1 个类似结果的用户展示呢?
  • 我的意思是,如果user_1 设置了two 兴趣,那么如果标签之一与其他用户相似,则此代码向用户显示,但我试图显示是否有超过 2 个标签相似然后显示用户。
  • 非常好,欢迎您!如果您想从列表中排除当前用户,我还更新了我的答案。
  • 请检查更新的答案以匹配具有多个兴趣的用户。我还没有测试过,但是类似的东西应该可以工作。
猜你喜欢
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2021-06-03
  • 2021-01-22
  • 2021-01-22
  • 2021-07-30
  • 1970-01-01
相关资源
最近更新 更多