OK so if you suggest edits to the documentation here, that would help.
Below is a working example where I basically cut-and-pasted directly
from the documentation example. The import for
"sqlalchemy.orm.interfaces" is missing, otherwise everything works as
advertised just by changing the arguments in the example to match the
use case. Let me know what needs clarification here, thanks!
from sqlalchemy import create_engine
e = create_engine("sqlite://", echo=True)
e.execute("""
create table a (id integer primary key, data varchar)
""")
e.execute("""
create table b (id integer primary key, data varchar,
foreign key (id) references a(id))
""")
# now i cut and paste from the automap docs at
#
http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/automap.html#custom-relationship-arguments
from sqlalchemy.ext.automap import generate_relationship
# this import is missing from the docs, OK.
from sqlalchemy.orm import interfaces
def _gen_relationship(
base, direction, return_fn,
attrname, local_cls, referred_cls, **kw):
if direction is interfaces.ONETOMANY:
# I change this line
kw['uselist'] = False
# default naming scheme for onetomany will
# come up with "<tablename>_collection", so chop that
# off assuming we want to do onetoone
if attrname.endswith("_collection"):
attrname = attrname[:-11]
return generate_relationship(base, direction, return_fn,
attrname, local_cls, referred_cls, **kw)
from sqlalchemy.ext.automap import automap_base
Base = automap_base()
# change this to point to the engine above
Base.prepare(
e, reflect=True,
generate_relationship=_gen_relationship)
# end-cut and paste. now im using it
A = Base.classes.a
B = Base.classes.b
from sqlalchemy.orm import Session
s = Session(e)
s.add(A(data="some a", b=B(data="some b")))
s.commit()
a1 = s.query(A).first()
assert a1.b.data == "some b"
> <
http://datadb.Cube.pk>))
> cube = relationship(datadb.Cube, backref='dap', uselist=False)
>
> # Prepare the base
> Base.prepare(engine, reflect=True,
> classname_for_table=camelizeClassName,
> name_for_collection_relationship=pluralize_collection,
> generate_relationship=_gen_relationship)
>
> # Explicitly declare classes
> for cl in Base.classes.keys():
> exec('{0} = Base.classes.{0}'.format(cl))
>
> --
> 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
sqlalchemy+...@googlegroups.com
> <mailto:
sqlalchemy+...@googlegroups.com>.
> To post to this group, send email to
sqlal...@googlegroups.com
> <mailto:
sqlal...@googlegroups.com>.
> Visit this group at
https://groups.google.com/group/sqlalchemy.
> For more options, visit
https://groups.google.com/d/optout.