Hello!
From reading the docs, I assumed that using "backref" on the child's
orm.relation declaration in a 1:n relationship is equivalent to using
"back_populates" with explicit orm.relation declarations on both ends.
However, it turns out that I get double insertions when using
back_populates - so, in the following code
p = Parent('parent1')
c = Child('child1')
c.parent = p
p.children.append(c)
p's children will contain c *twice*. Is this a bug, or am I reading
the docs wrong?
I'm grateful for any insights in this matter,
Oliver
=============
Class definitions:
class Child(object):
def __init__(self, name):
self.name = name
self.id = None
self.parent = None
class Parent(object):
def __init__(self, name):
self.name = name
self.id = None
self.children = []
Table definitions:
parent_table = sa.Table('parent', metadata,
sa.Column('parent_id', sa.types.Integer,
primary_key=True),
sa.Column('parent_name', sa.types.String,
nullable=False),
)
child_table = sa.Table('child', metadata,
sa.Column('child_id', sa.types.Integer,
primary_key=True),
sa.Column('child_name', sa.types.String,
nullable=False),
sa.Column('parent_id', sa.types.Integer,
sa.ForeignKey
(parent_table.c.parent_id),
nullable=False),
)
Mappers using backref:
orm.mapper(Parent, parent_table,
properties=
dict(name=orm.synonym('parent_name'),
id=orm.synonym('parent_id'),
)
)
orm.mapper(Child, child_table,
properties=
dict(parent=orm.relation(Parent,
uselist=False,
backref='parent'
),
name=orm.synonym('child_name'),
id=orm.synonym('child_id')
)
)
Mappers using back_populates:
orm.mapper(Parent, parent_table,
properties=
dict(name=orm.synonym('parent_name'),
id=orm.synonym('parent_id'),
children=orm.relation(Child,
back_populates='parent',
),
)
)
orm.mapper(Child, child_table,
properties=
dict(parent=orm.relation(Parent,
uselist=False,
back_populates='children',
),
name=orm.synonym('child_name'),
id=orm.synonym('child_id')
)
)