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?

1

5 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.

5

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.

1
is_active = Column(Boolean, server_default='t', default=True)
5

If someone is looking for a solution and using Flask this is how you'd do it.

It is very important to note that server default should be used inside the migrations file, not on the model itself.

once you generate migrations using a

flask db migrate

you should see new migration in the folder ( migrations/versions/XXXXXX.py )

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('confirmed', sa.Boolean(), nullable=True, server_default='f'))
    op.add_column('users', sa.Column('confirmed_on', sa.DateTime(), nullable=True))
    op.add_column('users', sa.Column('is_admin', sa.Boolean(), nullable=True, server_default='f'))

This is the place where you'd want to add server_default.

Provided solutions here don't work for me (SQLAchemy 1.4.40)

def test_entity():
    class Entity(Base):
        __tablename__ = "test_entities"
        id = Column(BigInteger, primary_key=True)
        is_active = Column(Boolean, nullable=False, default=True)

    entity = Entity()
    assert entity.is_active is True
Expected :True
Actual   :None
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest