2010-04-13 63 views
17

我想從表中獲取所有行。sqlalchemy,選擇所有行

在控制器I具有:

meta.Session.query(User).all() 

結果是[, ],但是我有在該表2點的行。

我使用的這款型號爲表:

import hashlib 
import sqlalchemy as sa 
from sqlalchemy import orm 

from allsun.model import meta 

t_user = sa.Table("users",meta.metadata,autoload=True) 

class Duplicat(Exception): 
    pass 
class LoginExistsException(Exception): 
    pass 
class EmailExistsException(Exception): 
    pass 

而接下來,在同一個文件:

class User(object): 
    def loginExists(self): 
     try: 
      meta.Session 
       .query(User) 
       .filter(User.login==self.login) 
       .one() 
     except orm.exc.NoResultFound: 
      pass 
     else: 
      raise LoginExistsException() 

    def emailExists(self): 
     try: 
      meta 
       .Session 
       .query(User) 
       .filter(User.email==self.email) 
       .one() 
     except orm.exc.NoResultFound: 
      pass 
     else: 
      raise EmailExistsException() 


    def save(self): 
     meta.Session.begin() 
     meta.Session.save(self) 
     try: 
      meta.Session.commit() 
     except sa.exc.IntegrityError: 
      raise Duplicat() 

orm.mapper(User, t_user) 

。 。 。 。 。 。 。 。

+7

沒有足夠的信息來重現您的問題。什麼是[[]]?這不是有效的python表達式,而是看起來像是在沒有正確轉義它的情況下,在HTML上打印兩個項目'[<用戶實例在...>,<用戶實例在...>]''的列表。 – 2010-04-14 03:46:39

+0

爲了解決你可以'從瓶子導入標記'然後'返回標記(「%r」)%User.query.all()'。 – 2014-09-23 15:39:35

回答

25

您可以輕鬆導入模型,並運行此:

from models import User 

# User is the name of table that has a column name 
users = User.query.all() 

for user in users: 
    print user.name