问题
I have the following class for a table in SQLalchemy
class STDcodes(db.Model):
id = db.Column(db.Integer, primary_key=True)
stdcode = db.Column(db.Integer, nullable=False)
city = db.Column(db.String(30), nullable=False)
state = db.Column(db.String(30), nullable=False)
def __init__(self, stdcode, city, state):
self.stdcode = stdcode
self.city = city
self.state = state
def __repr__(self):
return '<City {}>'.format(self.city)
Now I have a text file with some city names. I want to find the cities in the above database and replace their state value with something else("Telangana") I'm trying to use the following code for doing that.
from flask_hello_world_app import db, STDcodes
f = open('telanganastd.txt')
lines = f.readlines()
for line in lines:
line=line.replace("\n","")
print line
stdcode = STDcodes.query.filter_by(STDcodes.city.startswith(line))
stdcode.state= "TELANGANA"
db.session.add(stdcode)
db.session.commit()
But it doesn't work. I get the following error:
Traceback (most recent call last):
File "/home/alan/Desktop/Python books/Numbersindia/replacetelangana.py", line 10, in <module>
stdcode = STDcodes.query.filter_by(STDcodes.city.startswith(line)).first()
TypeError: filter_by() takes exactly 1 argument (2 given)
回答1:
Use filter, not filter_by. filter_by is a shortcut to filter that applies the equality op to keyword args, you can't use it for other ops.
filter takes operations, such as User.name == 'davidism' or STDcodes.city.startswith(line), and applies them to the query. filter_by is a shortcut that takes keyword arguments instead of operations, and expands them into the equivalent equality operations. So filter_by(name='davidism', superuser=True) is equivalent to filter(User.name == 'davidism', User.superuser).
So filter_by can be convenient but has limitations: all keywords are assumed to be columns on the primary model being filtered, the only operation supported is equality, and all operations are and'd together, there's no way to use or.
来源:https://stackoverflow.com/questions/28006507/getting-errors-with-passing-parameters-with-fliter-by-function-in-sqlalchemy