jazzband / django-taggit

Simple tagging for django
https://django-taggit.readthedocs.io
BSD 3-Clause "New" or "Revised" License
3.27k stars 623 forks source link

Cannot query using tags__name__in #889

Open marcrleonard opened 4 months ago

marcrleonard commented 4 months ago

Django Version: 4.2.9 Taggit Version: 5.0.1

Hello, I have been beating my head against this and cannot figure it out. I am using the through parameter to point to a UUID tag class. Here is my setup:

import uuid

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model

from taggit.managers import TaggableManager
from taggit.models import GenericUUIDTaggedItemBase, TagBase

class AssetTag(TagBase):
    user = models.ForeignKey(
        get_user_model(),
        related_name="assettag",
        on_delete=models.CASCADE
    )
    class Meta:
        verbose_name = _("Tag")
        verbose_name_plural = _("Tags")

class AssetTaggedItem(GenericUUIDTaggedItemBase):
    tag = models.ForeignKey(
        AssetTag,
        related_name="assettaggeditem",
        on_delete=models.CASCADE
    )
    class Meta:
        verbose_name = _("Tag")
        verbose_name_plural = _("Tags")

class Asset(models.Model):
    id = models.CharField(primary_key=True, max_length=36, default=uuid.uuid4, editable=False, db_index=True)
    user_id = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )
    tags = TaggableManager(through=AssetTaggedItem)

I will create an asset and tag it with some_tag ... then I try to query assets with the tag like this:

_t = AssetTag.objects.filter(name='some_tag').values_list('name', flat=True)
assets = Asset.objects.filter(tags__name__in=_t).distinct()

or assets = Asset.objects.filter(tags__name__in=["some_tag"]).distinct()

Both return no results. I cannot figure out whats going on.

rtpg commented 4 months ago

First question: If you do AssetTag.objects.all(), do you see the tag you are expecting to find? Like you're sure the tag is saved? I'm assuming that this database is pretty small.

Second question: if you have a specific asset, does asset.tags.objects.all() give you the tags you're expecting in general?

Sometimes it is helpful to do things like:

print(Asset.objects.filter(tags__name__in=["some_tag"]).query)

This should help you see what exactly your system is doing.