python 2.7 - Querying many-to-many in SQL Alchemy -
i have 2 two tables related third relationship table. basically, have many fits, can use number of tags, , i'm trying query fits tagged tag using tagid.
tag.py:
tags_table = table("tags", saveddata_meta, column("tagid", integer, primary_key = true), column("name", string, nullable = false, unique=true)) mapper(tag, tags_table)
fit.py (stripped down)
fits_table = table("fits", saveddata_meta, column("id", integer, primary_key = true), column("ownerid", foreignkey("users.id"), nullable = true, index = true), column("name", string, nullable = false), column("timestamp", integer, nullable = false)) fit_tags = table("fit_tags", saveddata_meta, column("fitid", integer, foreignkey("fits.id"), primary_key = true), column("tagid", integer, foreignkey("tags.tagid"), primary_key = true)) mapper(fit, fits_table, properties = { "_fit__tags" : relation(tag, secondary=fit_tags, backref="fits"), })
and here's function trying use:
def getfitswithtag(tagid, ownerid=none, where=none, eager=none): """ fits tag tagid if no user passed, users. """ if isinstance(tagid, int): if ownerid not none , not isinstance(ownerid, int): raise typeerror("ownerid must integer") filter = tag.tagid == tagid if ownerid not none: filter = and_(filter, fit.ownerid == ownerid) filter = processwhere(filter, where) eager = processeager(eager) sd_lock: fits = saveddata_session.query(fit).options(*eager).filter(filter).all() else: raise typeerror("tagid must integer") return fits
i can access tags of fit via fit._tags
. however, not sure how query fits based on tag. i've tried many values filter
i've come across while trying figure out.
add following line query:
def getfitswithtag(tagid, ownerid=none, where=none, eager=none): # ... fits = (saveddata_session.query(fit) .join(fit_tags).filter(fit_tags.c.tagid == tagid) # @note: add me .options(*eager).filter(filter) ).all() # ... return fits
also, why such strange name (_fit__tags
) relationship? guess coming django. since sqlalchemy not give special meanings in those, can name tags
.
Comments
Post a Comment