Hi all,

I'd like to have an Entity able to be "attached" to N different others,
avoiding the need of N intermediate/secondary tables.

I imagine something like the following::

  class Address(Base):
      __tablename__ = 'addresses'
      id = Column(Integer, primary_key=True)
      attached_kind = Column(String)
      attached_to = Column(Integer)

      street = Column(String)
      city = Column(String)
      state = Column(String)
      zip = Column(String)

  class Person(Base):
      __tablename__ = 'persons'
      id = Column(Integer, primary_key=True)
      name = Column(String)
      addresses = relationship(
        Address,
        uselist=True,
        primaryjoin="and_(Address.attached_to==Person.id, 
Address.attached_kind='Person')")

  class Home(Base):
      __tablename__ = 'homes'
      id = Column(Integer, primary_key=True)
      name = Column(String)

      addresses = relationship(
        Address,
        uselist=True,
        primaryjoin="and_(Address.attached_to==Home.id, 
Address.attached_kind='Home')")
    
This is really a variant of 
http://docs.sqlalchemy.org/en/rel_1_1/orm/join_conditions.html#specifying-alternate-join-conditions
except that the Address entity carries a tuple of (remote_object_kind,
remote_object_id) that uniquely identify the related object.

The above partially works, but as explained in the doc, SA does not populate
the "attached_*" fields when I do something like::

  newaddr = Address(street='somewhere')
  person.addresses.append(newaddr)

so I have to do this instead::

  newaddr = Address(street='somewhere', attached_kind='Person', 
attached_id=person.id)

Is there any trick hidden somewhere, or do I need a add_address() method on
each entity?

Thank you for any hint,
ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  |                 -- Fortunato Depero, 1929.

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to