One-to-one relationship as a boolean flag

11 views
Skip to first unread message

Pedro Werneck

unread,
Jul 8, 2015, 12:15:35 AM7/8/15
to sqlal...@googlegroups.com

Let's say I have a table 'user', and for backwards compatibility reasons I have a single-column table named 'user_active' which is basically just a foreign key used as a boolean flag. I need my User model to have the 'active' field as a boolean mapped to that one-to-one relationship. So, I have something like this:


class User(db.Model):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer, primary_key=True)
    # ... other fields

    active = relationship('UserActive', backref='user', uselist=False)


class UserActive(db.Model)
    __tablename__ = 'user_active'
    user_id = db.Column(db.Integer, db.ForeignKey('user.user_id')


Using the simple relationship like that returns either the UserActive instance, or None, which isn't ideal as True or False but works fine in any boolean context. My problem is assignment and querying. How can can I get it to work in a way that setting User.active = True creates the new UserActive instance, and querying for User.active == True works as a join, not a subquery?

Mike Bayer

unread,
Jul 8, 2015, 10:19:45 AM7/8/15
to sqlal...@googlegroups.com
why not make a @hybrid_property called "active", call the relationship _active, and then customize access completely?





--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Pedro Werneck

unread,
Jul 15, 2015, 1:02:23 PM7/15/15
to sqlalchemy
I thought maybe there was a simpler way to do that, but the
hybrid_property works. Thanks.
> You received this message because you are subscribed to a topic in the
> Google Groups "sqlalchemy" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/sqlalchemy/7azas9khOx0/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> sqlalchemy+...@googlegroups.com.
> To post to this group, send email to sqlal...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.



--
---
Pedro Werneck
Reply all
Reply to author
Forward
0 new messages