1
我正在學Python的SQLAlchemy。爲什麼我的SQLAlchemy query.flter只適用於某些屬性?
下面是我正在使用的一個示例。
首先我生成一個數據文件包含了諸如以下的小狗信息:
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()
現在我想過濾某些種類如下小狗:
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)
然後很奇怪,因爲testpuppy通過,我可以得到露西,但出生日期無法通過,每次我想要得到這些小便宜時,我只是得到一個錯誤
NameError: name 'dateOfBirth' is not defined
我真的不明白,爲什麼我的過濾器只能在某些屬性上操作,哪裏出錯?
酷,它的工作原理,並感謝您進一步ref :) – jetorz
@jetorz乾杯;) –