最新消息:这里是最新消息

flask_sqlalchemy数据库筛选日期 以及其他常用条件

python benty 374浏览 0评论

在做数据库查询的时候,自己有这样一个需求,需要将time字段查找等于哪一天的数据,但是time字段保存着精确到毫秒的datetime类型数据,所以我们需要做个转换.

 

id exe_time profiletest financeapi gzw_supervision
1 2021-06-23 00:00:00.000000 正常 正常 正常

例如上面,我们需要查找时间等于2021-06-23的,在python的flask中用orm怎么去写样例呢,

# 查询时间等于某一天的
start=datetime.datetime.strptime(“2021-06-23″,”%Y-%m-%d”)
    alld=Gold.query.filter(extract(‘year’,Gold.exe_time)==start.year,
                            extract(‘month’,Gold.exe_time)==start.month,
                            extract(‘day’,Gold.exe_time)==start.day
    )
上面的语句就可以查询到时间等于指定的日期当天的数据

flask数据库返回字典问题,默认返回basequery对象,想要返回字典,需要自己定义一个函数用来自己处理.

 

#model_to_dict 模型数据转换为字典.返回结果[{字典}]这样的格式
def mtd(result):
    # 转换完成后,删除  ‘_sa_instance_state’ 特殊属性
    try:
        if isinstance(result, Iterable):
            tmp = [dict(zip(res.__dict__.keys(), res.__dict__.values())) for res in result]
            for t in tmp:
                t.pop(‘_sa_instance_state’)
        else:
            tmp = dict(zip(result.__dict__.keys(), result.__dict__.values()))
            tmp.pop(‘_sa_instance_state’)
        # 对时间对象进行转换
        tmp[‘exe_time’]=tmp[“exe_time”].strftime(“%Y-%m-%d”)
        return tmp
    except BaseException as e:
        print(e.args)
        raise TypeError(‘Type error of parameter’)
# 接着调用这个函数就可以转换了
alld=Gold.query.filter(Gold.xxtime >= xxxx)
if not alld:
        return {“msg”:”没有数据”,”total”:0}
    result=[mtd(x) for x in alld]
    # 将时间对象转换为固定格式的时间日期
    # result[‘exe_time’]=result[“exe_time”].strftime(“%Y-%m-%d”)
    return {“msg”:”查询成功”,”total”:len(result),”data”:result}
上面就解决了字典调用问题
————
flask的模型查询的filter和filter_by的区别
Model.query.filter(Model.字段>=或==)这里传入的参数必须还要用Model.字段进行处理,等于是==
Model.query.filter_by(字段=xx)这里一般适合查找精准的数据,不用到Model名,一个等于号,字段=xx

下面再写一些关于Model.query.filter(这里一些参数)  的用法

 

equals:   

query.filter(User.name=='ed')

not equals:

query.filter(User.name!='ed')

like:

query.filter(User.name.like('%ed%'))

in:

query.filter(User.name.in_(['ed','wen','jask']))

not in:

query.filter(~User.name.in_(['ed','wen','jask']))

in null:

 query.filter(User.name==None)

is not null:

query.fillter(User.name!=None)

and:

query.filter(and_(User.name=='ed',Username=='ed jones'))

or:

query.filter(or_(User.name= 'ed',User.name=='wendy')

match:

query.filter(User.name.match('wendy'))

match() 使用特定于数据库的匹配或包含函数;它的行为会随着后端而变化,并且在诸如SQLite这样的一些后端是不可用的。

all(): 

返回一个列表

first():

    返回至多一个结果,而且以单项形式,而不是只有一个元素的tuple形式返回这个结果

one():

返回且仅返回一个查询结果。当结果的数量不足一个或者多于一个时会报错

one_or_one():

当结果数量为0时返回None, 多于1个时报错

scalar():

成功则返回该行的第一列的列号

text():

>>> from sqlalchemy import text
sql>>> for user in session.query(User).\
… filter(text(“id<224”)).\
… order_by(text(“id”)).all():
… print(user.name)

ed
wendy
mary
fred

params():传递参数

>>> session.query(User).filter(text(“id<:value and name=:name”)).params(value=224, name=’fred’).order_by(User.id).one()
<User(name=’fred’, fullname=’Fred Flinstone’, password=’blah’)>

from_statement():直接使用完整的SQL语句,但是要注意将表名和列名写正确

>>> session.query(User).from_statement(
text(“SELECT * FROM users where name=:name”)).\
params(name=‘ed’).all()
[<User(name=‘ed’, fullname=‘Ed Jones’, password=‘f8s7ccs’)>]
count():返回符合条件的总数
>>> session.query(User).filter(User.name.like(‘%ed’)).count()
func_count():可以直接指出要测次数的某一项
 from sqlalchemy import func
 session.query(func.count(User.name), User.name).group_by(User.name).all()
[(1, u’ed’), (1, u’fred’), (1, u’mary’), (1, u’wendy’)]

===========================

 

 

0000

转载请注明:稻香的博客 » flask_sqlalchemy数据库筛选日期 以及其他常用条件

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址