简体   繁体   中英

Using a variable in sqlalchemy query

I am trying to form a query in sqlalchemy but not sure how I can achieve this. I want to be able to use the variable in my query

 dog_type = 'pug'
 dog_name = 'buddy'
 .filter (animal.dogs.pug == 'buddy')

This is what I want it to be like:

.filter (animal.dogs.<dog_type> == <dog_name>)

While researching a bit about this I found some ways to do a similar thing.

  1. Using kwargs as filter parameter
  2. using getattr like this:

     .filter(getattr(animal, dogs) == 'buddy') 

however both the options don't seem to be working for my case or atleast for what I have tried. So any suggestion how could do this?

This is how filter works. first define a model:

class Dog(Base):
    __tablename__ = "dogs"

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

then import this class in your code:

import Dog

then you can query it like this:

pugs = db_session.query(Dog).filter(Dog.name == "pug").all()

for pug in pugs:
    print("I'm a pug in the database! I have ID " + str(pug.id))

Figured out the solution to my problem. Nesting getattr solved the problem.

animal_type = 'dogs'
dog_type = 'pug'
dog_name = 'buddy'
.filter(getattr(getattr(animal, animal_type), dog_type) == dog_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM