Model by name in SQLAlchemy

Is it possible to get a model class with ORM mapping on behalf of?

Definitely SQLAlchemy has built-in functionality. For example, in a declarative style, you can write things like blahs = relationship('Blah') (note: no module prefix is ​​required). I tried to look inside sqlalchemy.orm.properties.RelationshipProperty , but I can not understand when the argument string is replaced with the actual thing.

+4
source share
1 answer

The solution is not publicly available; the sqlalchemy.ext.declarative._deferred_relationship function is sqlalchemy.ext.declarative._deferred_relationship , and it has a nested (hidden) resolve_arg function.

The function uses the following logic to resolve names:

 def access_cls(key): if key in cls._decl_class_registry: return _GetColumns(cls._decl_class_registry[key]) elif key in cls.metadata.tables: return cls.metadata.tables[key] elif key in cls.metadata._schemas: return _GetTable(key, cls.metadata) else: return sqlalchemy.__dict__[key] 

where cls is a declarative class (derived from Base ). As you can see from the code, one way to resolve the name is to use the cls._decl_class_registry structure defined by the Foo class, you can enable the 'Blah' string for the class using Foo._decl_class_registry['Blah'] .

The ._decl_class_registry structure is just a python dict ; you can also specify your own cartographer when creating the Base class:

 class_registry = {} Base = declarative_base(class_registry=class_registry) 

and then you can search for classes directly in the class_registry mapping.

+7
source

All Articles