radiac / django-tagulous

Fabulous Tagging for Django
http://radiac.net/projects/django-tagulous/
Other
338 stars 66 forks source link

Look Up with Q object #39

Open rikachet1 opened 6 years ago

rikachet1 commented 6 years ago

I am trying to filter using tags created with taguluous. However, when using the Q object to filter the tags, it comes up with this error

Exception Value: invalid literal for int() with base 10: '(my tag)'

where the line of code the error appears is in : recipe_list= RecipePage.objects.filter(Q(recipeName__icontains = word) | **Q(tags = word)**)

In my models.py:

class RecipePage(models.Model):
    user = models.ForeignKey(CustomUser)
    recipeName = models.CharField(max_length=100)
    tags = TagField(
        force_lowercase=True,
        max_count=5,
    )

Let me know if there's another or better way to use multiple arguments to filter my queryset!

Thank you!

radiac commented 6 years ago

While Tagulous tries to make the TagField a first-class citizen in Django, it does so by overriding things in managers, querysets etc - and I hadn't tried it with Q objects! At some point I'll need to look at if I can override that, but I'm really struggling for time at the moment, so it's going to be a while before I can take a look.

In the meantime, it's failing because tags is actually a M2M field, so the filter call will be expecting the Q object to look by primary key, in this case an int.

You should be able to fix it with:

recipe_list = RecipePage.objects.filter(
    Q(recipeName__icontains = word) |
    Q(tags__name__icontains = word)
)

Note I also added the __icontains, because we're now bypassing Tagulous's string matching logic, so it will ignore your case_sensitive tag option.