Getting errors with passing parameters with fliter_by function in SQLAlchemy

六眼飞鱼酱① 提交于 2019-12-12 05:16:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!