python - How do I extend a SQLAlchemy bound declarative model with extra methods? -


for example, have declarative class on module a:

class user(base):     __tablename__ = 'users'      id = column(integer, primary_key=true)     name = column(string(50))     addresses = relationship("address", backref="user") 

now, in module b want use mapped entity, add method:

from import user  class userwithextramethod(user):     def name_capitalized(self):         return self.name.capitalize()  user = userwithextramethod() print(user.name_capitalized) 

however, when run script, following error:

invalidrequesterror: multiple classes found path "user" in registry of declarative base. please use module-qualified path. 

what have missed when declaring user entity? reuse previous declared entity.

i expecting like:

class userwithextramethod(user):     ___magic_reuse_previous_mapper__ = true      def name_capitalized(self):         return self.name.capitalize() 

unless you've got particular reason have separate classes, should write:

class user(base):     __tablename__ = 'users'      id = column(integer, primary_key=true)     name = column(string(50))     addresses = relationship("address", backref="user")      def name_capitalized(self):         return self.name.capitalize() 

since name_capitalized not special far sqlalchemy concerned (it's not columnexpression or such), ignored mapper.

actually, there's better way this; version works fine instances of user, of no use in sql expressions.

from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method class user(base):     # ... body before      @hybrid_method     def name_capitalized(self):         return self.name.capitalize()      @name_capitalized.expression     def name_capitalized(cls):         # works postgresql, other databases spell differently.         return sqlalchemy.func.initcap(cls.name) 

which allow things like:

>>> print query(user).filter(user.name_capitalized() == "alice") select users.id users_id, users.name users_name  users  initcap(users.name) = :initcap_1 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -