2015-11-28 91 views
3

我在SQLAlchemy中使用sqlite。我有一個類(修剪),像這樣定義的:Flask-SQLAlchemy SQLITE布爾型字段總是返回False

class User(db.Model): 
    __tablename__ = 'users' 
    id = db.Column(db.Integer, primary_key=True) 
    can_view_records = db.Column(db.Boolean, default=False, nullable=False) 

隨着我的架構,像這樣定義的:

create TABLE users (
    id INTEGER not null, 
    can_view_records BOOLEAN not null, 
    PRIMARY KEY (id) 
); 

在我的數據庫,我有以下行:

+----+------------------+ 
| id | can_view_records | 
+----+------------------+ 
| 8 | 1    | 
| 9 | 0    | 
+----+------------------+ 

查詢他們在Python中總是給我Falsecan_view_records字段。

>>> User.query.get(8).can_view_records 
False 
>>> User.query.get(9).can_view_records 
False 

但在該領域進行過濾成功:

>>> User.query.filter_by(can_view_records=True).all() 
[<id 8>] 

,但這樣的結果有個返回False:

>>> User.query.filter_by(can_view_records=True).first().can_view_records 
False 

我缺少的東西?

回答

0

具有相同的代碼可以在OSX與Python 2.7.10SQLAlchemy==1.0.9Flask-SQLAlchemy==2.1不會重現,Flask==0.10.1

#!/usr/bin/env python 
# encoding: utf-8 

from flask import Flask 
from flask_sqlalchemy import SQLAlchemy 

app = Flask(__name__) 
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' 
db = SQLAlchemy(app) 


class User(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    username = db.Column(db.String(80), unique=True) 
    email = db.Column(db.String(120), unique=True) 
    can_view_records = db.Column(db.Boolean, default=False, nullable=False) 

    def __init__(self, username, email, can_view_records): 
     self.username = username 
     self.email = email 
     self.can_view_records = can_view_records 

    def __repr__(self): 
     return '<User %r>' % self.username 

產生DB:

>>>from app import db, User 
>>>db.create_all() 
>>>admin = User('admin', '[email protected]', True) 
>>>guest = User('guest', '[email protected]', False) 
>>>db.session.add(admin) 
>>>db.session.add(guest) 
>>>db.session.commit() 

SQLite表看起來是這樣的:

sqlite> select * from user; 
1|admin|[email protected]|1 
2|guest|[email protected]|0 

所有查詢看起來都是oka y:

>>>User.query.get(1).can_view_records 
>>>True 
>>>User.query.get(2).can_view_records 
>>>False 
>>>User.query.filter_by(can_view_records=True).first().can_view_records 
>>>True