I save email addresses in two tables: userid and domain. The model looks something like this:
class Email():
id = Column(Integer, primary_key=True)
parent_id = Column(Unicode, ForeignKey('domain.id'))
parent = relationship('Domain')
userid = Column(Unicode)
class Domain():
id = Column(Integer, primary_key=True)
host = Column(Unicode)
I suddenly started having issues with joins. When I do the following, I always get None:
def get_email(email):
fragments = email.lower().split(u'@')
return DBSession().query(Email).filter(Email.userid == fragments[0]).join(Domain, Domain.id == Email.parent_id).filter(Domain.host == fragments[1]).first()
But if I separate this join into two queries, I retrieve the correct object:
def get_email(email):
fragments = email.lower().split(u'@')
session = DBSession()
thehost = session.query(Domain).filter(Domain.host == fragments[1]).first()
return session.query(Email).filter(Email.userid == fragments[0]).filter(Email.parent_id == thehost.id).first()
Anyone know what I’m doing wrong, or how I should go about troubleshooting? I spent the last 30 minutes to no avail… Thanks!
Figured out the problem. Had to do with inheritance and aliasing. Lesson: If joining two objects inherited from the same object, alias at least one of the objects!