为什么我的SQLAlchemy query.flter只对某些属性起作用?

2024-09-30 02:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学习Python的炼金术

下面是我正在使用的一个例子

首先,我生成一个包含小狗信息的数据文件,如下所示:

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)

然后很奇怪,因为测试小狗通过了,我可以得到露西,但出生日期不能通过,每次我想得到这些小小狗,我只是得到了一个错误

NameError: name 'dateOfBirth' is not defined

我真的不明白,为什么我的过滤器只能对某些属性进行操作,哪里出错了


Tags: nameidnewtodaynamessessioncolumngender
1条回答
网友
1楼 · 发布于 2024-09-30 02:16:08

问题是您需要使用filter而不是filter_by,如下所示:

smallpuppy = session.query(Puppy).filter(Puppy.dateOfBirth < birthdate)

对于filter,条件应该使用ClassName.propertyName访问列,您可以使用<>

对于filter_by,条件可以是直接使用propertyName访问列,但不能使用<>

请参考this answer,它将为您提供有关filterfilter_by之间差异的更多详细信息

相关问题 更多 >

    热门问题