2012-07-19 11 views
10

Mam relację wiele do wielu między powiedzeniem wpisów blogu i znacznikami. Teraz chcę wiedzieć, ile wpisów ma określony tag.Liczba wierszy w relacji wiele do wielu (SQLAlchemy)

Wyobraźmy sobie następujące modele (uproszczony):

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 

moje podejście do zliczania ilości wpisów dla tagu jest len(db_session.query(Tag).get(1).entries). Problem polega na tym, że gdy pobiera się db_session.query(Tag).get(1).entries SQLAlchemy wybiera wszystkie wpisy ze wszystkimi kolumnami dla znacznika, jednak chcę tylko ilość wpisów, a nie same wpisy. Czy istnieje bardziej optymalne podejście do tego problemu?

Dzięki.

Odpowiedz

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

lub jeśli masz już Tag

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

+1: a jeśli trzeba to często można utworzyć właściwość: '@property \ n def entries_cnt (self): \ n return Session.object_session (self) .query (Entry) .with_parent (self, "entries"). count() ' – van

+0

Dzięki za tę odpowiedź. Jednak wyprodukowana instrukcja SQL to "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'' Innymi słowy - zamiast jednego 'SELECT count (*) FROM order_line WHERE order_line.order_id =% (param_1) s' otrzymujemy wewnętrzny SELECT. W moim przypadku nie jest jeden-do-wielu (Zamówienie ma wiele linii zamówienia). – guyarad

+0

wykonaj zapytanie (func.count ('*')) z góry. dokumentacja [count()] (http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=query.count#sqlalchemy.orm.query.Query.count) odnosi się do tego. – zzzeek

Powiązane problemy