SQLAlchemy

时间:2016-12-06 12:55:50

标签: python json postgresql sqlalchemy

这是我的音频表的模型:

class Audio(db.Model):
    __tablename__ = "audio"

    id = db.Column(db.Integer, primary_key=True)
    file_location = db.Column(db.String(), unique=True)
    upload_time = db.Column(ArrowType, default=arrow.utcnow())
    keyword = db.Column(JSON)
    transcript = db.Column(JSON)
    diarization = db.Column(JSON)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id', onupdate='cascade', ondelete='cascade'))
    company_id = db.Column(db.Integer, db.ForeignKey('company.id', onupdate='cascade', ondelete='cascade'))
    client_id = db.Column(db.Integer, db.ForeignKey('client.id', onupdate='cascade', ondelete='cascade'))

    def __init__(self, file_location, upload_time, keyword, transcript, diarization, user_id, company_id, client_id):
        self.file_location = file_location
        self.upload_time = upload_time
        self.keyword = keyword
        self.transcript = transcript
        self.diarization = diarization
        self.user_id = user_id
        self.company_id = company_id
        self.client_id = client_id

    def __repr__(self):
        return '<Audio ID %r>' % self.id

这是成绩单字段中的数据:

{"transcript": [
    {"duration": 2390.0, 
    "interval": [140.0, 2530.0], 
    "speaker": "Speaker_2", 
    "words": [
        {"p": 0, "s": 0, "e": 320, "c": 0.545, "w": "This"}, 
        {"p": 1, "s": 320, "e": 620, "c": 0.825, "w": "call"}, 
        {"p": 2, "s": 620, "e": 780, "c": 0.909, "w": "is"}, 
        {"p": 3, "s": 780, "e": 1010, "c": 0.853, "w": "being"}, 
        {"p": 4, "s": 1010, "e": 1250, "c": 0.814, "w": "recorded"}
        ]
    }, 
    {"duration": 4360.0, 
    "interval": [3280.0, 7640.0], 
    "speaker": "Speaker_1", 
    "words": [
        {"p": 5, "s": 5000, "e": 5020, "c": 0.079, "w": "as"},
        {"p": 6, "s": 5020, "e": 5100, "c": 0.238, "w": "a"},
        {"p": 7, "s": 5100, "e": 5409, "c": 0.689, "w": "group"},
        {"p": 8, "s": 5410, "e": 5590, "c": 0.802, "w": "called"},
        {"p": 9, "s": 5590, "e": 5870, "c": 0.834, "w": "tricks"}
        ]
    },
    ...
} 

我有一个postgresql查询,我试图在SQLAlchemy中执行此操作:

SELECT words['p']
FROM (
    SELECT transcript_info['words'] AS info
    FROM Audio, func.json_array_elements(transcript['transcript']) AS transcript_info) AS t,
    func.json_array_elements(info) AS words
WHERE words['w'] ILIKE 'this';

这就是我想出来的:

db = create_engine('postgresql://localhost/test', echo=True)
db.echo = True

Session = sessionmaker(bind=db)
session = Session()

from app.models import User, Company, Client, Audio 

metadata = MetaData(db)

def run(stmt):
    rs = stmt.execute()
    for row in rs:
        print row


selectable = Audio.transcript['transcript']['words']
s = select(selectable['p']).filter(Audio.transcript['transcript']['words']['w'].ilike('this'))
run(s)


s = select(Audio.user_id)

我得到了这个结果:

TypeError: 'builtin_function_or_method' object is not iterable

我不确定为什么它不可迭代。

0 个答案:

没有答案