I'd use a property for that, one that tests if the user_id
column is not NULL. A column_property()
seems appropriate here:
from sqlalchemy.orm import column_property
class Address(Base):
...
user_id = Column(Integer, ForeignKey('user.id'))
IsItAssigned = column_property(user_id != None)
Now IsItAssigned
will be either True
or False
. Alternatively, use a hybrid property:
from sqlalchemy.ext.hybrid import hybrid_property
class Address(Base):
...
user_id = Column(Integer, ForeignKey('user.id'))
@hybrid_property
def IsItAssigned(self):
return self.user_id != None
A hybrid property has the advantage of being usable in a query as well. Last but not least, for this case, perhaps an ordinary property would do too, it'll only work on already loaded instances though:
class Address(Base):
...
user_id = Column(Integer, ForeignKey('user.id'))
@property
def IsItAssigned(self):
return self.user_id is not None
I'd use a different name, though. assigned
might be better; the Python style guide (PEP 8) advocates the lower_case_with_underscores
for methods and instance attributes.