Hello everyone!
Let's say I have a class defined like this:
class User(declarativeBase):
"""Represents a user"""
__tablename__ = "users"
_id = Column("id", Integer, primary_key=True)
_phone = Column("phone", String(16))
_userName = Column("user_name", String(50), unique=True, nullable=False)
_password = Column("password", String(64), nullable=False)
_userGroupId = Column("user_group_id", Integer,
ForeignKey("user_groups.id"))
_userGroup = relationship("UserGroup", uselist=False)
def setId(self, id):
"""Set id"""
self._id = int(id)
def getId(self):
"""Get id"""
return self._id
def setUserGroupById(self, userGroupId):
userGroupId = int(userGroupId)
if userGroupId != self.userGroupId:
self.userGroup = UserGroupManager.getById(userGroupId)
def setUserGroup(self, userGroup):
"""Set user group"""
if isinstance(userGroup, UserGroup):
self._userGroup = userGroup
else:
raise TypeError("Trying to set a " +
str(type(userGroup)) + " as user group")
def getUserGroup(self):
"""Get user"""
return self._userGroup
#More getters/setters
id = sqlalchemy.orm.synonym('_id', descriptor=property(getId, setId))
phone = sqlalchemy.orm.synonym('_phone',
descriptor=property(getPhone, setPhone))
userName = sqlalchemy.orm.synonym('_userName',
descriptor=property(getUserName, setUserName))
password = sqlalchemy.orm.synonym('_password',
descriptor=property(getPassword, setPassword))
userGroupId = sqlalchemy.orm.synonym('_userGroupId',
descriptor=property(getUserGroup, setUserGroup))
userGroup = sqlalchemy.orm.synonym('_userGroup',
descriptor=property(getUserGroup, setUserGroup))
I have created an utility that, given an instance gives me the names
of the synonyms in said instance.
def getProperties(instance):
properties = list()
mapper = sqlalchemy.orm.object_mapper(instance)
for prop in mapper.iterate_properties:
if isinstance(prop, sqlalchemy.orm.properties.SynonymProperty):
properties.append(prop.key)
return properties
That would give me ["id", "phone", "userName", "password",
"userGroupId", "userGroup"], so I can more or less generically go
through all said values and execute things like
for attribute in getProperties(instanceOfUser):
value = getattr(instanceOfUser, attribute)
Is there any way of knowing that said "value"s are ForeignKeys or
relationships? For instance, I'd like to know that the attribute "id"
is a regular (well... kind of regular... it's a Primary key, but it's
not going to point to anything in another table) numeric attribute,
but "userGroupId" is a foreign key and "userGroup" is a Relationship.
I've been sneaking in the vars, __dict__, dir of the values returned
by getattr, but I haven't been able to find anything suitable.
Thank you!
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.