Python 使用长生不老药创建生成性搜索
我一直在使用长生不老药,我现在有一个非常混乱的方法来搜索数据库,我想改进一下。文档提供了如何进行基本的生成性搜索的见解,但我需要逐步浏览许多不同的类,我更喜欢使用Elixir,而不是自己浏览列表 下面是一个例子:Python 使用长生不老药创建生成性搜索,python,sqlalchemy,tornado,python-elixir,Python,Sqlalchemy,Tornado,Python Elixir,我一直在使用长生不老药,我现在有一个非常混乱的方法来搜索数据库,我想改进一下。文档提供了如何进行基本的生成性搜索的见解,但我需要逐步浏览许多不同的类,我更喜欢使用Elixir,而不是自己浏览列表 下面是一个例子: Class Student: hobby = Field(String) additional_info = OneToOne('AdditionalInformation', inverse='student') user_profile = OneToOne('UserProfil
Class Student:
hobby = Field(String)
additional_info = OneToOne('AdditionalInformation', inverse='student')
user_profile = OneToOne('UserProfile', inverse='student')
Class AdditionalInformation:
state = Field(String)
city = Field(String)
student = OneToOne('Student', inverse='additional_info')
Class UserProfile:
username = Field(String)
date_signed_up = Field(DateTime)
student = OneToOne('Student', inverse = 'user_profile')
在本例中,我想找出所有学生:
result = UserProfile.query.filter_by(date_signed_up>2008)
result.query.filter_by(UserProfile.student.hobby='blabla')
result.query....
目前,我正在将它们放入一个列表并寻找一套。我没有使用长生不老药,但我使用了SQLAlchemy。我不认为你能做你想做的,因为目前的设置。据我所知,没有办法直接按关系过滤 目前还不清楚您是在创建新表还是在处理现有表,因此我将向您提供一些信息,希望其中一些信息对您有所帮助 您可以在SQLAlchemy中将表连接在一起(假设UserProfile上有一个名为student_id的外键)。这将给你所有从2008年起注册的学生
result = Student.query.join(UserProfile).filter(Student.id==UserProfile.student_id).filter(UserProfile.date_signed_up>2008).all()
您可以像上面那样将.filter()链接在一起,也可以将多个参数传递给它们。我发现这对于处理未知数量的过滤器特别有用,就像你从搜索表单中得到的一样
conditions = [UserProfile.date_signed_up>2008]
if something_is_true:
conditions.append(UserProfile.username=="foo")
result = Student.query.join(UserProfile).filter(Student.id==UserProfile.student_id).filter(and_(*conditions)).all()
还有更复杂的东西,你可以做混合属性,但这似乎不适合这里