【发布时间】:2015-01-18 07:45:19
【问题描述】:
我在 SQLAlchemy 中有以下表类:
class pinCodes(db.Model):
id = db.Column(db.Integer, primary_key=True)
officename = db.Column(db.String(60), nullable=False)
pincode = db.Column(db.Integer, nullable=False)
taluk = db.Column(db.String(50), nullable=False)
district = db.Column(db.String(50), nullable=False)
state = db.Column(db.String(50), nullable=False)
__tablename__ = "pincodes"
def __init__(self, officename, pincode, taluk, district, state):
self.officename = officename
self.pincode = pincode
self.taluk = taluk
self.district = district
self.state = state
def __repr__(self):
return '<officename {}>'.format(self.officename)
现在我想返回所有带有“pincode”的列作为特定值: 代码如下:
def fmt_pin(code):
return code.replace(" ","").replace("-","").replace("_","").strip()
def int_pin(code):
code = fmt_pin(code)
return int(code)
@app.route('/find_pin_codes', methods=['POST','GET'])
def pincodes():
if request.method == 'POST':
if request.form.get("pincode", "") != "":
pincode = request.form['pincode']
try:
num = pinCodes.query.filter(pincode = int_pin(pincode)).all()
return render_template('pincodes.html',
bypincode = num
)
except Exception as e:
return render_template('pincodes.html',
error = e)
但是当我搜索一个数字时,我收到以下错误: filter() 得到了一个意外的关键字参数“pincode”。
编辑:使用 filter_by 后,我没有得到任何结果。 这是我的 Jinja 模板代码:
{% if pincode is defined %}
<thead>
<tr>
<td><h4>Pincode</h4></td>
<td><h4>Office Name</h4></td>
<td><h4>Taluk</h4></td>
<td><h4>District</h4></td>
<td><h4>State</h4></td>
</tr>
</thead>
<tbody>
{% for o in bypincode %}
<tr>
<td><h5>{{ o.pincode }}</h5></td>
<td><h5>{{ o.officename }}</h5></td>
<td><h5>{{ o.taluk }}</h5></td>
<td><h5>{{ o.district }}</h5></td>
<td><h5>{{ o.state }}</h5></td>
</tr>
{% endfor %}
{% endif %}
【问题讨论】:
-
顺便说一句,你不需要
!= '',因为空字符串在Python中是假的。 -
在我删除 {% if pincode is defined %} 后它现在可以工作了
标签: python python-2.7 flask flask-sqlalchemy