在常规sql中我可以通过“select * from table”拉出整个列,我找不到sqlalchemy中的等价物。
我正在尝试从我的表User中提取所有用户名。到目前为止我找到的只是models.User.query.all(),然后执行for循环来拉出我想要的列,但我认为这是一个糟糕的做法,因为当我只需要1时它会拉动整个表列。
models.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), index=True, unique=True)
password_hash = db.Column(db.String(128))
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
#mobilitys = db.relationship('Mobility', backref='username', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
def __repr__(self): # pragma: no cover
return '<user> %r' % (self.username)
终端尝试使用_实体
>>> from app import db, models
>>> models.User.query.with_entities(User.username)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'User' is not defined
>>> models.User.username
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7fccb4f682f0>
后续问题的终端视图:
jsnyder10@jsnyder10-VirtualBox:~$ cd Documents/45
jsnyder10@jsnyder10-VirtualBox:~/Documents/45$ source env/bin/activate
(env) jsnyder10@jsnyder10-VirtualBox:~/Documents/45$ flask/bin/python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from models import User
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named models
>>> from .models import User
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
第二终端视图:
(env) jsnyder10@jsnyder10-VirtualBox:~/Documents/45$ flask/bin/python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db, models
>>> from models import User
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named models
>>> from .models import User
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Attempted relative import in non-package
答案 0 :(得分:1)
您可以尝试使用with_entities()方法来限制您希望在结果中返回哪些列。例如:
result = session.query(User.username)
或使用sqlalchmey会话:
string only_key = dict.Keys.Single();