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')
5
  • These 2 questions explore dynamic schema with declarative classes: stackoverflow.com/questions/29595161/… and stackoverflow.com/questions/39863337/…. The solutions aren't pretty and if you really need it, you'll have to become familiar with dynamic classs creation. Commented Mar 27, 2017 at 20:00
  • Fixed the typo. Thanks I think I'll just add a user_type column and avoid the extra schemas Commented Mar 27, 2017 at 20:17
  • Have you had a look at SQLAlchemy's inheritance strategies? That might be close to what you're doing, and with concrete table inheritance you could split those tables to different schemas, while having a User class hierarchy in python. Commented Mar 27, 2017 at 20:25
  • Yes I'm using Mixins docs.sqlalchemy.org/en/latest/orm/extensions/declarative/… Commented Mar 27, 2017 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. Commented Mar 27, 2017 at 21:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.