我的查询未在我的数据库中显示所有结果

时间:2015-01-12 01:39:29

标签: python database flask sqlalchemy

我目前在我的数据库中有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

2 个答案:

答案 0 :(得分:0)

您只返回compaigns中的第一个campaign_list,因为在第一个循环中您返回函数。试试这个:

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

答案 1 :(得分:0)

或许,尝试使用join

将2合并为1个简单函数
def get_subscribers_by_user():
    subscribers = Subscriber.query.\
                             join(Campaign).\
                             filter(Campaign.user_id == g.user.id).all()
    return subscribers