Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy boolean value is None

I have this table in my Pyramid app

class User(Base):     __tablename__ = 'users'     id = Column(Integer, primary_key=True)     .....     is_active = Column(Boolean, unique=False)     def __init__(self, name, raw_password):         is_active = True 

When I did my test, it said is_active is None.

def test_register_user(self):     user = User('user1', '1234')     self.sess.add(user)     self.sess.flush()      #print user     #self.assertTrue(user.is_active, True)     user_db_record = self.sess.query(User).filter_by(name=user.name).first()     self.assertEqual(user_db_record.is_active, True) 

From my integration log I see when we are creating the row, is_active is set to None. Why?

like image 297
user1012451 Avatar asked Aug 20 '12 21:08

user1012451


People also ask

How to insert a null value in SQLAlchemy?

fromsqlalchemyimportnullconn.execute(table.insert(),{"json_value":null()}) To insert or select against a value that is JSON "null", use the constant JSON.NULL: conn.execute(table.insert(),{"json_value":JSON. NULL})

What is the issue number for SQLAlchemy on GitHub?

· Issue #5613 · sqlalchemy/sqlalchemy · GitHub Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails. Already on GitHub?

What is SQLAlchemy and how does it work?

Column and Data Types¶ SQLAlchemy provides abstractions for most common database data types, and a mechanism for specifying your own custom data types. The methods and attributes of type objects are rarely used directly.

Where can I find more information about SQLAlchemy API?

You may check out the related API usage on the sidebar. You may also want to check out all available functions/classes of the module sqlalchemy.types , or try the search function .


2 Answers

You have to set a default value otherwise None/NULL is used:

is_active = Column(Boolean, unique=False, default=True) 

You wanted to do this in __init__ but you used is_active = True (a local variable) instead of self.is_active = True.

like image 96
Jochen Ritzel Avatar answered Oct 14 '22 13:10

Jochen Ritzel


If you're using Flask-SQLAlchemy, you can use this command to create a server side default.

from sqlalchemy.sql import expression active = db.Column(db.Boolean, server_default=expression.true(), nullable=False) 

This will create a default value on the database so anyone can write to it and the DB will have the default value.

like image 39
Sowmitra Nalla Avatar answered Oct 14 '22 14:10

Sowmitra Nalla