I have an Entries model that has tags, so every entry can have many tags. Tags are a model with a value of tag which is the tag string. I am trying to filter my returned entries on sets of tags. For instance, given two tags, a and b, I want to return only the entries that have both tag a and tag b.
Right now I have OR, in the sense that I can return any entries that have either a or b and I have done it this way.
entObjs = Entries.query.join(Entries.tags).filter(Tags.tag.in_(tagList)).all()
tagList is a list of strings. How do I implement the AND, so I get only entries that have all the tags?
I did something similar using aliased tables and joins,
from sqlalchemy.orm import aliased
def test(self, tags):
q = self.session.query(models.Item).\
join(models.ItemTag).\
join(models.Tag.\
filter(models.Tag.name == tags[0])
i = 0
for tag in tags[1:]:
alias1 = aliased(models.Tag)
alias2 = aliased(models.ItemTag)
q = q.join(alias2, models.Item.id == alias2.item_id).\
filter(alias1.id == alias2.tag_id).\
filter(alias1.name == tag)
i += 1
print(str(q))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments