*The goal*
I have an ORM model.
class MyModel(Model):
__tablename__ = 'my_model'
col1 = db.Column(db.Boolean, default=False, server_default=false())
col2 = db.Column(db.Integer, default=100, server_default=null())
I want to be able to create an object and have col1 and col2 be populated
with default values even before the object is committed or even added to a
session.
For example:
>>> print(MyModel().col1)
False
>>> print(MyModel().col2)
100
I came across this answer by Mike Bayer:
http://stackoverflow.com/a/14013090/925675 where he recommends using either
__init__() or events.
I decided to use to an event based solution, but I did not want to
duplicate default values in the listener function, so I trying to do it in
the following way:
@event.listens_for(MyModel, 'init')
def init(target, args, kwargs):
target_type = type(target)
for attr_name in ('col1', 'col2'):
attr_default = getattr(target_type, attr_name).default
if attr_default is None:
continue
elif attr_default.is_callable:
kwargs.setdefault(attr_name, attr_default.arg())
elif attr_default.is_scalar:
kwargs.setdefault(attr_name, attr_default.arg)
else:
raise AttributeError("Unsupported default type of column {}".
format(attr_name))
So far it works for my need, except 2 issues:
1) It does not work with Sequential or Clause defaults, which I don't have
need for anyway.
2) It completely relies on ColumnDefault internals and partially duplicates
logic from DefaultExecutionContext._exec_default()
I am wondering if there is a better solution to it?
Thanks,
Anton.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.