我有一个查询,该查询返回一个User
对象。 User
个已完成的Post
个。执行查询时,我想根据特定时间过滤在User.post
中找到的帖子。例如,仅返回给定时间戳记1天内的帖子。
class User(base):
__tablename__ = 'User'
class Post(base):
__tablename__ = 'Post'
user_id = Column(Integer, ForeignKey('User.uid'))
user = relationship(User, backref=backref('post')
time = Column(DateTime, default=func.current_timestamp())
是否有一种方法可以动态更改orm加载子级的方式,并在查询时进行指定?类似于(伪代码):
User.query.filter_child(Post.time in timespan)
重要的是,如果没有符合条件的孩子,我不想过滤掉父母。我只想过滤orm为给定用户加载的子代。
答案 0 :(得分:2)
Loading custom filtered collections使用contains_eager()
完成。由于目标是加载所有import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import flask
import io
from dash.dependencies import Input, Output, State
# import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Dropdown(
id='dropdown',
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': 'Montreal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
value='NYC'
),
html.A('Download',
id='download',
href=''),
# dcc.Store(id='data_store',storage_type='memory'),
])
# Calculate the data and store it.
@app.callback(
Output('download', 'href'),
[Input('dropdown', 'value')])
def update(value):
return '/download_csv/get_it?value={}'.format(value)
@app.server.route('/download_csv/get_it')
def download_excel():
param = flask.request.args
print(param)
# Dummy dataframe for downloading.
d = {'col1': param['value'],'col2': 'Did it change?'}
df = pd.DataFrame(data=d,index=[0])
#Convert DF
str_io = io.StringIO()
df.to_csv(str_io, sep=",")
mem = io.BytesIO()
mem.write(str_io.getvalue().encode('utf-8'))
mem.seek(0)
str_io.close()
return flask.send_file(mem,
mimetype='text/csv',
attachment_filename='downloadFile.csv',
as_attachment=True)
if __name__ == '__main__':
app.run_server(debug=True)
对象,即使它们没有符合过滤条件的User
对象,也应使用Post
并将帖子的谓词放入{{1 }}的子句:
outerjoin()
答案 1 :(得分:0)
我不确定这是您要找的东西,但是这种KISS方法有什么问题呢?
Post.query.filter(Post.user == <username>).filter(
Post.time > START_OF_DAY).filter(Post.time < END_OF_DAY).all()