Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter exact through tags #840

Open
pancakeDevelopment opened this issue Dec 27, 2022 · 6 comments
Open

Filter exact through tags #840

pancakeDevelopment opened this issue Dec 27, 2022 · 6 comments

Comments

@pancakeDevelopment
Copy link

pancakeDevelopment commented Dec 27, 2022

I'm trying to do this:

_q =  ["tag1","tag2]

Message.objects.filter(Q(tags__name__in=_q)).distinct().order_by('timestamp')

Now I want a result, where every message has exact those two tags - not just one of them. I've tried it with __name__exact=_q, but it isn't working. Any ideas how to solve this issue?

@rtpg
Copy link
Contributor

rtpg commented Jan 8, 2023

I haven't tried this but I believe that doing Message.objects.filter(tags__name="tag1").filter(tags__name="tag2") should give you what you want.

That should return your messages that include tag1.... that are then filtered down by messages including tag2 (so the end result has those including both).

If you want to find those with exactly those two tags (i.e. no other tags), then you will want to filter those down, then there's a bit more work involved.

has_both_tags = Message.objects.filter(tags__name="tag1").filter(tags__name="tag2")

# get all the tag objects that you are not interested in (using the through model)
all_other_tags = Message.tags.through.objects.exclude(name__in=["tag1", "tag2")
# filter out messages that have any of those other tags
only_both_tags = has_both_tags.exclude(tags__in=all_other_tags)

I haven't tested this but the through model should be helpful for you. Core idea, mathematically is:

  • get the set of messages with both tags
  • get all the tags that you do not care about
  • get the set of messages with any tags you don't care about
  • exclude that latter set from this set

@rtpg rtpg added the question label Jan 8, 2023
@developcreativo

This comment was marked as off-topic.

@developcreativo

This comment was marked as off-topic.

@developcreativo

This comment was marked as off-topic.

@ethagnawl

This comment was marked as duplicate.

@rtpg
Copy link
Contributor

rtpg commented Jun 24, 2024

We might want to document how to do this kind of search, how to get objects that have exactly a certain set of tags. We could put this into the FAQs inside the documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants