我的查询没有显示数据库中的所有结果
My query doesn't show all results in my database
目前我的数据库中有 3 条记录应该显示,但我只看到 3 条记录中的 2 条。
只是为了让您了解发生了什么:
订阅者 1 和订阅者 2 的活动 ID 为 1,订阅者 3 的活动 ID 为 2
但是,这两个订阅者都属于同一帐户创建的活动。
所以,我想要完成的是向订阅了他们的活动的帐户持有人显示。
谁能告诉我哪里做错了?
def get_campaign_subscribers():
# Get authenticated user campaigns and create a list
campaigns = Campaign.query.filter_by(user_id=g.user.id).all()
campaign_list = []
if campaigns:
for c in campaigns:
campaign_list.append(c.id)
for i in campaign_list:
return get_subscribers(i)
def get_subscribers(campaign_id):
subscribers = Subscriber.query.filter_by(campaign_id=campaign_id).all()
return subscribers
您只 return campaign_list
中的第一个 compaigns
,因为在第一个循环中您创建了函数 return。试试这个:
def get_campaign_subscribers():
# Get authenticated user campaigns and create a list
campaigns = Campaign.query.filter_by(user_id=g.user.id).all()
campaign_list = []
if campaigns:
for c in campaigns:
campaign_list.append(c.id)
# return a list which is result of get_subscribers by passing through items in campaign_list
return map(get_subscribers, campaign_list)
def get_subscribers(campaign_id):
subscribers = Subscriber.query.filter_by(campaign_id=campaign_id).all()
return subscribers
或者,尝试使用 join
:
将 2 个组合成 1 个简单函数
def get_subscribers_by_user():
subscribers = Subscriber.query.\
join(Campaign).\
filter(Campaign.user_id == g.user.id).all()
return subscribers
目前我的数据库中有 3 条记录应该显示,但我只看到 3 条记录中的 2 条。
只是为了让您了解发生了什么:
订阅者 1 和订阅者 2 的活动 ID 为 1,订阅者 3 的活动 ID 为 2 但是,这两个订阅者都属于同一帐户创建的活动。 所以,我想要完成的是向订阅了他们的活动的帐户持有人显示。
谁能告诉我哪里做错了?
def get_campaign_subscribers():
# Get authenticated user campaigns and create a list
campaigns = Campaign.query.filter_by(user_id=g.user.id).all()
campaign_list = []
if campaigns:
for c in campaigns:
campaign_list.append(c.id)
for i in campaign_list:
return get_subscribers(i)
def get_subscribers(campaign_id):
subscribers = Subscriber.query.filter_by(campaign_id=campaign_id).all()
return subscribers
您只 return campaign_list
中的第一个 compaigns
,因为在第一个循环中您创建了函数 return。试试这个:
def get_campaign_subscribers():
# Get authenticated user campaigns and create a list
campaigns = Campaign.query.filter_by(user_id=g.user.id).all()
campaign_list = []
if campaigns:
for c in campaigns:
campaign_list.append(c.id)
# return a list which is result of get_subscribers by passing through items in campaign_list
return map(get_subscribers, campaign_list)
def get_subscribers(campaign_id):
subscribers = Subscriber.query.filter_by(campaign_id=campaign_id).all()
return subscribers
或者,尝试使用 join
:
def get_subscribers_by_user():
subscribers = Subscriber.query.\
join(Campaign).\
filter(Campaign.user_id == g.user.id).all()
return subscribers