2016-02-04 26 views
0

我在哪裏存儲鼠標的ID和FMRI測量會話,類數據庫(具有大大降低的列,爲方便起見)如下所示:從查詢中選擇鏈接的對象中的SQLAlchemy

class FMRIMeasurement(Base): 
    __tablename__ = "fmri_measurements" 
    id = Column(Integer, primary_key=True) 
    date = Column(DateTime) 
    animal_id = Column(Integer, ForeignKey('animals.id')) 

class Animal(Base): 
    __tablename__ = "animals" 
    id = Column(Integer, primary_key=True) 
    id_eth = Column(Integer) 
    fmri_measurements = relationship("FMRIMeasurement", backref="animal") 

我想創建一個熊貓數據框,以獲得分配給某個特定動物的所有FMRIMeasure的所有細節。從動物中選擇數據正常工作:

mystring = str(session.query(Animal).filter(Animal.id_eth == 1)) 
print pd.read_sql_query(mystring, engine, params=[4001]) 

但只要我儘量選擇FMRIMeasurements它炸燬。以下的工作都沒有。

mystring = str(session.query(Animal.fmri_measurements).filter(Animal.id_eth == 1)) 

mystring = str(session.query(FMRIMeasurement).filter(FMRIMeasurement.animal.id_eth == 1)) 

mystring = str(session.query(Animal.fmri_measurements.date).filter(Animal.id_eth == 1)) 

我猜我只是用SQLAlchemy的錯,但我找不到任何事情來幫助我與我的使用情況下,在文檔(或許,我不知道該怎麼wthat我想要做的實際上是調用): -/

回答

1

session.query使得查詢字符串,你需要使用.first().all()得到結果集

例如實際執行它

sql_query = session.query(Animal.fmri_measurements).filter(Animal.id_eth == 1) 

result_set = sql_query.all() # execute the query and return resultset 

for item in result_set: 
    # do work with item 

    # if the item changes and you want to commit the changes 
    session.merge(item) 

# commit changes 
session.commit() 

Alterantively你不需要的。所有(),並通過查詢對象迭代將執行它,以及

sql_query = session.query(Animal.fmri_measurements).filter(Animal.id_eth == 1) 
for item in sql_query: 
    #do something 

爲了再拿到熊貓數據框,你可以運行:

mystring = str(session.query(Weight)) 
print pd.read_sql_query(mystring,engine) 
+0

謝謝你答案。我其實有一個後續問題,但我認爲它足夠大,可以在單獨的頁面上更好地適應這裏的評論。你能幫我嗎? http://stackoverflow.com/questions/35208961/filter-query-by-linked-object-key-in-sqlalchemy基本上這個解決方案工作,如果列包含蜇,浮游物,Ints,但它不起作用,如果我想按相關對象過濾。 – TheChymera