1

I'm having a hard time figuring out SQLAlchemy constructors http://docs.sqlalchemy.org/en/latest/orm/constructors.html What I would like is to pass a schema parameter to a class constructor as follows but I get 'self' is not defined errors.

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    __table_args__ = {'schema' : self.s}
    def __init__(self, s):
        self.s = s

u = User('customschema')
user1071182
  • 1,609
  • 3
  • 20
  • 28
  • These 2 questions explore dynamic schema with declarative classes: http://stackoverflow.com/questions/29595161/sqlalchemy-dynamic-schema-on-entity-at-runtime and http://stackoverflow.com/questions/39863337/sqlalchemy-orm-with-dynamic-table-schema. The solutions aren't pretty and if you really need it, you'll have to become familiar with [dynamic classs creation](http://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class). – Ilja Everilä Mar 27 '17 at 20:00
  • Fixed the typo. Thanks I think I'll just add a user_type column and avoid the extra schemas – user1071182 Mar 27 '17 at 20:17
  • Have you had a look at [SQLAlchemy's inheritance strategies](http://docs.sqlalchemy.org/en/latest/orm/inheritance.html)? That might be close to what you're doing, and with [concrete table inheritance](http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#concrete-table-inheritance) you could split those tables to different schemas, while having a User class hierarchy in python. – Ilja Everilä Mar 27 '17 at 20:25
  • Yes I'm using Mixins http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html – user1071182 Mar 27 '17 at 20:44
  • Mixins are a bit different. They allow having common "traits" in a single class, and actual declarative classes then inheriting those "traits" (I might be misusing the word). Inheritance hierarchies allow mapping python class hierarchies to SQL relations. It also allows polymorphic loading, so a single query can return results of different types, for example different user types. – Ilja Everilä Mar 27 '17 at 21:04

0 Answers0