Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of rows in a many-to-many relationship (SQLAlchemy)

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.

like image 558
verbit Avatar asked Jul 19 '12 19:07

verbit


1 Answers

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()
like image 144
zzzeek Avatar answered Nov 01 '22 11:11

zzzeek