[英]Why my SQLAlchemy query.flter works only on some attribute?
I am learning SQLAlchemy of Python. 我正在学习Python的SQLAlchemy。
Below is an example I am useing. 以下是我正在使用的示例。
First I generate a datafile contains puppy information like below: 首先我生成一个数据文件包含如下的小狗信息:
class Puppy(Base):
__tablename__ = 'puppy'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
gender = Column(String(6), nullable = False)
dateOfBirth = Column(Date)
shelter_id = Column(Integer, ForeignKey('shelter.id'))
weight = Column(Numeric(10))
male_names = ["Bailey", "Max", ...just some names..., "Luke", "Henry"]
female_names = ['Bella', 'Lucy', ...just some names..., 'Honey', 'Dakota']
def CreateRandomAge():
today = datetime.today()
days_old = randint(0,540)
birthday = today - timedelta(days = days_old)
return birthday
def CreateRandomWeight():
return random.uniform(1.0, 40.0)
for i,x in enumerate(male_names):
new_puppy = Puppy(name = x, gender = "male", dateOfBirth = CreateRandomAge(), weight= CreateRandomWeight())
session.add(new_puppy)
session.commit()
for i,x in enumerate(female_names):
new_puppy = Puppy(name = x, gender = "female", dateOfBirth = CreateRandomAge(), weight= CreateRandomWeight())
session.add(new_puppy)
session.commit()
Now I want to filter some kinds of puppies as below: 现在我想过滤一些类型的小狗,如下所示:
testpuppy = session.query(Puppy).filter_by(name='Lucy')
print(testpuppy)
birthdate = datetime.today() - timedelta(days=180)
smallpuppy = session.query(Puppy).filter_by(dateOfBirth < birthdate)
print(smallpuppy)
Then it is strange, because the testpuppy passed, I can get Lucy, but the dateofBirth can not pass, every time I want to get these smallpuppies, I just got an error 然后很奇怪,因为testpuppy通过了,我可以得到Lucy,但是dateofBirth无法通过,每次我想得到这些小小狗,我只是得到一个错误
NameError: name 'dateOfBirth' is not defined
I really can not understand, why my filter can only be operated on some attribute, where is wrong? 我真的无法理解,为什么我的过滤器只能在某些属性上操作,哪里出错了?
The problem is that you need to use filter
instead of filter_by
like this: 问题是你需要使用filter
而不是filter_by
如下所示:
smallpuppy = session.query(Puppy).filter(Puppy.dateOfBirth < birthdate)
For filter
, the criterion should use ClassName.propertyName
to access the column, and you can use <
or >
. 对于filter
,标准应使用ClassName.propertyName
来访问列,您可以使用<
或>
。
For filter_by
, the criterion could be use propertyName
directly to access the column, but you cannot use <
or >
. 对于filter_by
,标准可以直接使用propertyName
来访问列,但不能使用<
或>
。
Please refer to this answer , it will give you more details about the difference between filter
and filter_by
. 请参考这个答案 ,它将为您提供有关filter
和filter_by
之间区别的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.