获取每个用户今日通知的最佳方式

时间:2014-01-23 14:16:59

标签: python sqlalchemy flask django-queryset

我正在研究样本应用程序以学习烧瓶,因为我有一些模型

class Followup(Base):

  __tablename__ = 'followup'
  id = Column(Integer, primary_key=True)
  status = Column(String(), nullable=False)
  next_date = Column(DateTime, default = datetime.utcnow())
  student_id = Column(Integer, ForeignKey('student.id'), nullable='True')
  prospect = relationship("Student", backref="followup")


class Student(Base):

  __tablename__ = 'student'
  id = Column(Integer, primary_key=True)
  name = Column(String(), nullable=False)
  email = Column(String(), nullable=False)
  address = Column(String(), nullable=False)
  status = Column(String(), nullable=False) #saving active, inactive values

我想获得所有学生今天的后续通知(如果有的话,我希望获得今天的学生对象,否则没有后续值)

result = db_session.query(Student, Followup.status).outerjoin(Followup).filter(Student.status == "active").all()

这里得到同一个学生的多个记录

如何通过今天的followp查询每个学生的记录

提前致谢

2 个答案:

答案 0 :(得分:1)

这是在一次往返中获取所有数据的查询:

today = datetime.today()
def get_data():
    """ @return: [(student, followup), (student, followup), ...] """
    q = (session.query(Student) # get all students
        .outerjoin(Followup, and_(Student.id == Followup.student_id, func.date(Followup.next_date)==today)) # @NOTE: check for today might need to be different depending on the database used. Current code should work for mysql
        .options(contains_eager(Student.followup)) # let SA know that "followup" is loaded (line above)
        .filter(Student.status == "active") # filter only for active students
        )
    res = [(s, s.followup) for s in q.all()]
    return res

data = get_data()

# debug
for s, f in data:
    print s.name
    for _f in f:
        print "  ", _f

答案 1 :(得分:0)

为什么不直接获取所有后续内容并过滤掉非活跃的学生?学生对象可从后续对象followup.prospect获得。

您可以在SQLAlchemy中执行此操作,或者只是获取所有后续内容并过滤掉非活动状态,如下所示:

followups = session.query(Followup).all()
active_followups = [f for f in followups if f.proscpect.status == "active"]