Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

python - Override default in sqlalchemy reflected tables

I've reflecting a load of tables in an exiting mysql db. I want to express that any columns of a certain name in any table default to datetime.now(). However naively looping through the tables and columns and just setting default on those I find that have a certain name doesn't work, When doing session.add(); session.flush() I get the following error:

AttributeError: 'builtin_function_or_method' object has no attribute '__visit_name__'

This would seem to be tied up in the call to _set_parent (and the this self._init_items(*toinit) at line 721 in sqlalchemy.schema.

Does anyone know if there's a way to do this without either going through all of my reflected tables and adding Column(..) lines every where all doing the same thing or resorting to really ugly hacks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another option is to override the columns that need defaults while reflecting:

Table('some_table', metadata,
    Column('create_time', DateTime, default=datetime.now),
    autoload=True)

Unfortunately you currently can't reflect the datatype and set SQLAlchemy side default at the same time. One could argue though that the datatype is part of the interface definition and so the redundancy doesn't create a maintenance issue - if the columns datatype changes you most likely need to change the default value function too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...