Rémy V.D
Rémy V.D

Reputation: 260

SQLAlchemy automap backref error

I have a huge problem with SQLAlchemy automap and overriding names. See the code below :

from sqlalchemy import create_engine, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.automap import automap_base
import re
import inflect
import warnings
from sqlalchemy import inspect

#name overriding
def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
    name = referred_cls.__name__.lower()
    local_table = local_cls.__table__
    if name in local_table.columns:
        newname = name + "_"
        warnings.warn(
            "Already detected name %s present.  using %s" %
            (name, newname))
        return newname
    return name

def camelize_classname(base, tablename, table):
    "Produce a 'camelized' class name, e.g. "
    "'words_and_underscores' -> 'WordsAndUnderscores'"

    return str(tablename[0].upper() + \
            re.sub(r'_([a-z])', lambda m: m.group(1).upper(), tablename[1:]))

_pluralizer = inflect.engine()
def pluralize_collection(base, local_cls, referred_cls, constraint):
    "Produce an 'uncamelized', 'pluralized' class name, e.g. "
    "'SomeTerm' -> 'some_terms'"

    referred_name = referred_cls.__name__
    uncamelized = re.sub(r'[A-Z]',
                         lambda m: "_%s" % m.group(0).lower(),
                         referred_name)[1:]
    pluralized = _pluralizer.plural(uncamelized)
    return pluralized


engine = create_engine(
    "mysql+pymysql://blablabla@blabla/blabla", convert_unicode=True)

db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
#Mapping
Base = automap_base()
Base.prepare(engine, reflect=True, name_for_scalar_relationship = name_for_scalar_relationship, classname_for_table=camelize_classname, name_for_collection_relationship=pluralize_collection)

I used all the overriding functions adviced by the documentation, and I still have this error :

sqlalchemy.exc.ArgumentError: Error creating backref 'order_supplier_rows' on relationship 'OrderSupplierRow.detail': property of that name exists on mapper 'Mapper|Detail|detail'

The problem is the same as in this previous post: sqlalchemy Error creating backref on relationship

Except I can't change the database definition to rename backrefs. Or it would be the very last solution, if nothing else is working... I would like to override these backref names if they already exist more than once during auto mapping.

I've been trying to fix this for hours ! Thanks in advance !

Upvotes: 3

Views: 1675

Answers (1)

Rémy V.D
Rémy V.D

Reputation: 260

Seems I solved the problem by overriding the backrefs naming:

def _gen_relationship(base, direction, return_fn,
                                attrname, local_cls, referred_cls, **kw):
    return generate_relationship(base, direction, return_fn,
                                 attrname+'_ref', local_cls, referred_cls, **kw)

before calling

Base.prepare(engine, reflect=True, generate_relationship=_gen_relationship)

Upvotes: 8

Related Questions