I have a many-to-many relationship between say blog entries and tags. Now I want to know how many entries a specific tag has.
Imagine the following models (simplified):
rel_entries_tags = Table('rel_entries_tags', Base.metadata,
Column('entry_id', Integer, ForeignKey('entries.id')),
Column('tag_id', Integer, ForeignKey('tags.id'))
)
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(String(80))
text = Column(Text)
tags = relationship('Tag', secondary=rel_entries_tags, backref=backref('entries'))
def __init__(self, title, text):
self.title = title
self.text = text
self.tags = tags
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
name = Column(String(80), unique=True, nullable=False)
def __init__(self, name):
self.name = name
My approach to count the amount of entries for a tag is len(db_session.query(Tag).get(1).entries)
. The problem is that when it gets db_session.query(Tag).get(1).entries
SQLAlchemy selects all the entries with all their columns for a tag, however, I want only the amount of the entries, not the entries themselves. Is there a more optimal approach for this problem?
Thanks.
session.query(Entry).join(Entry.tags).filter(Tag.id==1).count()
or if you have a Tag already
session.query(Entry).with_parent(mytag, "entries").count()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With