I’m trying to convert a one-to-many part of a many-to-many relationship to a python set(). See the following play example for code:
message_tos = Table('message_tos', Base.metadata,
Column('message_id', Integer, ForeignKey('message.id')),
Column('address_id', Integer, ForeignKey('address.id'))
)
class Address(Base):
address = Column(String, nullable=False, unique=True)
emails = relationship('Message')
def __init__(self, address):
self.address = address
class Email(Base):
from = relationship('Address', backref='from')
to = relationship('Address', secondary=message_tos, backref='messages_to')
message_id = Column(String, nullable=False, unique=True)
...
def whatever(*args, **kwargs):
"""
...
"""
email = session.query(Email).filter(Email.message_id==message_id).first()
blah = set(email.to).union(email.from) # This lines throws an error that Address is not iterable
Is there any way to run the set(email.to) code (which places an Address object into a set), or am I going about this completely the wrong way? Obviously, I could just do set([email.to]), however this is an entire extra order of complexity (and this function may be called multiple times with potentially very long .to or .from lists) which I’d rather not have
Your error most probably occurs not in the
set(email.to)part, but in.union(email.from), since theemail.fromis not iterable. According to your code,email.fromis an instance ofAddress.This should work though:
blah = set(email.to).union([email.from]). I assume that did not really call the propertyfrom, as it is a reserved keyword in python. I guesssenderis a good name.Also note that in SA searching for a primary key can be done clearer with the
Query.get: