2016-11-20 4 views
0

私は本当に基本的な日記アプリケーションを作成しています。 (プロジェクト名になります)Entry.textでグループにそれらを、その後SQLAlchemyの集計日の相違

association_table = Table('association', Base.metadata, 
    Column('category_id', Integer, ForeignKey('category.id')), 
    Column('entry_id', Integer, ForeignKey('entry.id')) 
) 

class Category(Base): 
    __tablename__ = 'category' 

    id = Column(Integer, primary_key=True) 
    name = Column(String(100), unique=True) 
    entries = relationship('Entry', secondary=association_table, 
          back_populates='categories') 

class Entry(Base): 
    __tablename__ = 'entry' 

    id = Column(Integer, primary_key=True) 
    text = Column(String(200)) 
    started = Column(DateTime) 
    ended = Column(DateTime) 
    categories = relationship('Category', secondary=association_table, 
           back_populates='entries') 

私はカテゴリの仕事 'でタグ付けされたすべてのエントリを取得したいと思い、そして:私はSQLAlchemyの中で次のようなモデルを持っています。私は基本的に各プロジェクトでどれぐらいの時間を費やしてきたのかを見たいと思っていますだから私は次のように書いています:

from sqlalchemy.sql import func 
# s is the Session 
work = s.query(Category).filter(Category.name=='work').first() 
projects = (s.query(Entry.text, 
        func.sum(Entry.ended-Entry.started) 
         .label('duration')) 
       .filter(Entry.categories.contains(work)) 
       .group_by(Entry.text) 
       .order_by('duration desc')) 

これはうまくいくようです。私はこのクエリを実行しようとすると、

>>> print str(projects) 
SELECT entry.text AS entry_text, sum(entry.ended - entry.started) AS duration 
FROM entry, association AS association_1 
WHERE entry.id = association_1.entry_id AND %(param_1)s = association_1.category_id 
GROUP BY entry.text ORDER BY duration desc 

しかし、私は次のエラーを取得する:

>>> projects.all() 
[...trace back...] 
TypeError: unsupported operand type(s) for -: 'Decimal' and 'datetime.datetime' 

私はSAを推測している実際には、それは私がMySQLのに対してそれを実行すると、直接は、DBありません何らかの処理をして失敗しようとしていますか?このクエリを機能させる方法はありますか?

答えて

0

データベースがMySQLの場合、SQLAlchemyはInterval(timedelta)演算を実行できません。

class tsum(GenericFunction): 
    type = Float() 
    name = 'SUM' 

projects = s.query(Entry.text, (func.t_sum(
       func.time_to_sec(func.timediff(Entry.ended, Entry.started)/60) 
        .label('duration')) 
      .filter(Entry.categories.contains(work)) 
      .group_by(Entry.text) 
      .order_by('duration desc') 

これは、タプル(text, minutes)を返すものです。