0

I have an assortment of sqlalchemy classes e.g:

class OneThing(Base):
    id = Column(Integer, Sequence('one_thing_seq'), primary_key=True)
    thing = Column(Boolean())
    tag = Column(String(255))


class TwoThing(Base):
    id = Column(Integer, Sequence('two_thing_seq'), primary_key=True)
    thing = Column(Boolean())
    tag = Column(String(100))

i.e. fairly standard class contructions for sqlalchemy

Question: Is there a way to get greater control over the column creation or does that need to be relatively static? I'd at least like to consolidate the more mundane columns and their imports across a number of files like this for example(not as a mixin because I already do that for certain columns that are the same across models, but a function that returns a column based on potential vars):

class OneThing(Base):
    id = Base.id_column()
    thing = Base.bool_column
    tag = Base.string_col(255)


class OneThing(Base):
    id = Base.id_column()
    thing = Base.bool_column
    tag = Base.string_col(255)

Seems simple enough and fairly approachable that I will just start reading/typing, but I have not found any examples or the proper search terms for examples, yet. There is no reason that class columns need to be static, and it is probably simple. Is this a thing, or a foolish thing?

2 Answers 2

1
from sqlalchemy import Column, Boolean, Integer

def c_id():
    return Column(Integer, primary_key=True)

def c_bool():
    return Column(Boolean, nullable=False, default=False)

def c_string(len):
    return Column(String(len), nullable=False, default='')

class Thing(Base):
    id = c_id()
    thing = c_bool()
    tag = c_string(255)

The SQLAlchemy developer goes into more detail here: http://techspot.zzzeek.org/2011/05/17/magic-a-new-orm/

Sign up to request clarification or add additional context in comments.

Comments

1

The Column() call is not magical; you can use any random way to create the appropriate object. The magic (i.e. binding the column to the variable name and the table) happens in Base's metaclass.

So one solution is for you to write your own code which returns a Column() or three -- nothing prevents you from doing this:

class Thing(Base):
    id,thing,tag = my_magic_creator()

On the other hand, you can drop all these assignments wholesale, and do the work in a metaclass; see my answer here: Creating self-referential tables with polymorphism in SQLALchemy for a template on how to do that.

Comments

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.