title: Count number of rows in a many-to-many relationship (SQLAlchemy)
body: <p>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.</p>
  
  <p>Imagine the following models (simplified):</p>
  
  <pre><code>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
  </code></pre>
  
  <p>My approach to count the amount of entries for a tag is <code>len(db_session.query(Tag).get(1).entries)</code>. The problem is that when it gets <code>db_session.query(Tag).get(1).entries</code> 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?</p>
  
  <p>Thanks.</p>