【问题标题】:Count number of rows in a many-to-many relationship (SQLAlchemy)计算多对多关系中的行数(SQLAlchemy)
【发布时间】:2012-07-20 04:01:12
【问题描述】:

我说博客条目和标签之间存在多对多的关系。现在我想知道一个特定标签有多少个条目。

想象以下模型(简化):

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

我计算标签条目数量的方法是len(db_session.query(Tag).get(1).entries)。问题是,当它获得db_session.query(Tag).get(1).entries SQLAlchemy 选择所有条目及其所有列作为标记,但是,我只想要条目的数量,而不是条目本身。有没有更优化的方法来解决这个问题?

谢谢。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:
    session.query(Entry).join(Entry.tags).filter(Tag.id==1).count()
    

    或者如果您已经有标签

    session.query(Entry).with_parent(mytag, "entries").count()
    

    【讨论】:

    • +1:如果你经常需要这个,你可以创建一个属性:@property\n def entries_cnt(self): \n return Session.object_session(self).query(Entry).with_parent(self, "entries").count()
    • 感谢您的回答。但是,生成的 SQL 语句是 SELECT count(*) AS count_1 FROM (SELECT order_line.id AS order_line_id, order_line.order_id AS order_line_order_id FROM order_line WHERE %(param_1)s = order_line.order_id) AS anon_1 换句话说 - 我们得到一个内部 SELECT 而不是一个 SELECT count(*) FROM order_line WHERE order_line.order_id = %(param_1)s。就我而言,它不是一对多的(Order 有很多 OrderLine)。
    • 预先做一个查询(func.count('*'))。 count() documentation 指的是这个。
    • 使用session.query(Entry).with_parent(mytag).count()也应该没问题。 The property parameter can be omitted
    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2015-08-11
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多