sqlalchemy可以只查某一列吗
(百度这个编辑功能太渣了,markdown/markup都不支持,缩进都没了,凑合看吧。)
注意以以下查询返回的不再是DeclarativeMeta对象,而是单纯的tuple对象,也就是说没有列名。
用query的with_entites方法:
User.query.with_entities(User.id,User.dept_id).all()
2.如果有外键关系,可以使用join进行关联,join的参数要用relationship的backref值:
# Model User
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(40), unique = True, nullable = False)
password = db.Column(db.String(32), nullable = False)
email = db.Column(db.String(120), unique = True)
realname = db.Column(db.String(20))
dept_id = db.Column(db.Integer, db.ForeignKey('department.id'))
def __init__(self, username, password, email, realname, dept_id):
self.username = username
self.password = password
self.email = email
self.realname = realname
self.dept_id = dept_id
#Model Department
class Department(db.Model):
id = db.Column(db.Integer, primary_key=True)
department_name = db.Column(db.String, unique=True, nullable=True)
users = db.relationship('User', backref='dept',lazy='dynamic')
def __init__(self,department_name):
self.department_name = department_name
def __repr__(self):
return '<Department %r>' % self.department_name
查询方法:
User.query.with_entities(User.id,User.username,Department.department_name).join(User.dept).all()
等价于:
SELECT "user".id AS user_id, "user".username AS user_username, department.department_name AS department_department_name FROM "user" JOIN department ON department.id = "user".dept_id
i.User.query.filter_by(username='peter').first(),通过filter_by方法里的条件表达式来对query所得到的结果集进行过滤,得到你想要得到的结果。
example:
Retrieve a user by username通过username属性为’peter‘过滤结果集:
>>> peter = User.query.filter_by(username='peter').first()
>>> peter.id
1
>>> peter.email
u'peter@example.org'
当不存在结果集时返回none:
>>> missing = User.query.filter_by(username='missing').first()
>>> missing is None
True