2012-07-19 59 views
10

我說博客條目和標籤之間有多對多的關係。現在我想知道特定標籤有多少個條目。計算多對多關係中的行數(SQLAlchemy)

想象一下以下機型(簡體):

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選擇標籤的所有列的所有條目,但是,我只想要條目的數量,而不是條目本身。這個問題有沒有更理想的方法?

謝謝。

回答

15
session.query(Entry).join(Entry.tags).filter(Tag.id==1).count() 

,或者如果你有一個標籤已經

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

+1:如果你需要經常這樣,你可以創建一個屬性:'@property \ n 高清entries_cnt(個體經營):\ n返回Session.object_session(self).query(Entry).with_parent(self,「entries」)。count() ' – van 2012-07-20 08:13:12

+0

感謝您的回答。但是,生成的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 count(*)FROM order_line WHERE order_line.order_id =%(param_1)s'我們得到一個內部SELECT。 在我的情況下,它不是一對多的(Order有很多OrderLine)。 – guyarad 2016-08-02 13:23:25

+0

預先查詢(func.count('*'))。 [count()文檔](http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query.count#sqlalchemy.orm.query.Query.count)引用此。 – zzzeek 2016-08-05 21:03:33

相關問題