1
Cynic222 2015-01-01 13:34:38 +08:00
没试过,但我猜可以session.add(Article(**data))
|
2
timonwong 2015-01-01 13:36:21 +08:00
http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#create-an-instance-of-the-mapped-class
如果你没有自定义 __init__ 方法,那么SQLAlchemy已经提供了一个keyword arguments的调用方法,你的代码就只需要: Article(**data) 就可以了 但是如果你自定义了__init__ 就不行了,要写个包装函数,比如from_dict PS, 这个是默认 __init__ 的实现: ``` def _declarative_constructor(self, **kwargs): """A simple constructor that allows initialization from kwargs. Sets attributes on the constructed instance using the names and values in ``kwargs``. Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships. """ cls_ = type(self) for k in kwargs: if not hasattr(cls_, k): raise TypeError( "%r is an invalid keyword argument for %s" % (k, cls_.__name__)) setattr(self, k, kwargs[k]) _declarative_constructor.__name__ = '__init__' ``` |
3
timonwong 2015-01-01 13:37:14 +08:00
|
4
yakczh OP @timonwong
articles_table = Table('articles',metadata, Column('id',Integer,primary_key=True), Column('title',String(40)), Column('author',String(40)), Column('content',String(40)), Column('ctime',Integer,default=0), Column('status',Integer,default=0), ) class Article(object): >>def __repr__(self): >>>>return "<Article('%s','%s','%s')>" % (self.title,self.author,self.content) mapper(Article,articles_table) data={"title":"xxxx","author":"oooo","content":"ksjfosjfos"} u=Article(**data) session.add(u) 运行提示: u=Article(**data) TypeError: __init__() got an unexpected keyword argument 'content' 很奇怪不报 title,author出错 |