Hello,
Today I have questions regarding generic associations and more specifically the table_per_association example:
I am trying to adapt it to the following case:
Here is my code:
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy import create_engine, Integer, Column, \
String, ForeignKey, Table
from sqlalchemy.orm import Session, relationship
@as_declarative()
class Base(object):
"""Base class which provides automated table name
and surrogate primary key column.
"""
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(Integer, primary_key=True)
class Object(Base):
name = Column(String, nullable=False)
class HasObjects(object):
@declared_attr
def objects(cls):
object_association = Table(
"%s_objects" % cls.__tablename__,
cls.metadata,
Column("object_id", ForeignKey("object.id"),
primary_key=True),
Column("%s_id" % cls.__tablename__,
ForeignKey("%s.id" % cls.__tablename__),
primary_key=True),
)
return relationship(Object, secondary=object_association)
# The following line doesn't works :
#
# return relationship(Object, secondary=object_association, backref="parent")
#
# Error :
#
# sqlalchemy.exc.ArgumentError: Error creating backref 'parent' on
# relationship 'ObjectContainer.objects': property of that name exists on mapper
# 'Mapper|Object|object'
class ObjectContainer(HasObjects, Base):
name = Column(String)
class Hands(HasObjects, Base):
name = Column(String)
engine = create_engine('sqlite://', echo=True)
Base.metadata.create_all(engine)
session = Session(engine)
session.add_all([
ObjectContainer(
name='Chest 1',
objects=[
Object(name="potion 1"),
Object(name="potion 2")
]
),
Hands(
name="Hands player 1",
objects=[
Object(name="potion 3"),
Object(name="potion 4")
]
),
])
session.commit()I have two questions:
I assume that the answers are pretty simple but I think my comprehension of the “secondary” parameter of relationship is not good enough to find a solution.
Thank you!
Sven
for customer in session.query(Customer):
for address in customer.addresses:
print(address)
print(address.parent) # this attribute is what I need