SQLAlchemy自动化backref错误

时间:2018-03-21 17:02:27

标签: python sqlalchemy

我对SQLAlchemy的自动化和覆盖名称有很大的问题。 请参阅以下代码:

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)

我使用了文档提供的所有重要功能,但仍然有这个错误:

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

问题与上一篇文章中的问题相同: sqlalchemy Error creating backref on relationship

除非我无法更改数据库定义以重命名backrefs 。或者它将是最后的解决方案,如果没有别的工作...... 我想覆盖这些反射名称,如果它们在自动映射期间已经存在多次。

我一直试图解决这个问题几个小时! 提前谢谢!

1 个答案:

答案 0 :(得分:1)

似乎我通过覆盖backrefs命名来解决问题:

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)

之前打电话

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