Search code examples
pythondjangodjango-modelsdjango-viewstags

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


I am building a BlogApp i am stuck on an Error.

What i am trying to do :- ( What i want it to do )

I am filtering users with similar tags. BUT when i try to filter then the error is keep showing -

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)

What have i tried :-

  • I also tried by
    users = Profile.objects.filter(interests=request.user.profile.interests.all())

BUT it shows this error

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

Any help would be much Appreciated.

Thank You in Advance.


Solution

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

    This fails with the error:

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

    Because, you are searching directly in interests which is an exact lookup. Because, interests of a user could be multiple, you need __in lookup:

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

    Please note, that this will also get the profile of the request.user so if you need to exclude that you can append .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.

    In this case, you can annotate on interests and use filter:

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