简体   繁体   English

SQLAlchemy实例的更简洁的初始化

[英]More succinct initialization for SQLAlchemy instance

It's my first attempt at sqlalchemy. 这是我第一次尝试sqlalchemy。 I have a json file with my usr information and I would like to put them in a sqlite3 database file. 我有一个包含我的usr信息的json文件,我想将它们放在sqlite3数据库文件中。 It works but I find the instance initialization verbose since there are many columns in the table, as you can see below. 它可以工作,但是我发现实例初始化很冗长,因为表中有很多列,如下所示。

Is it possible to use a dictionary as input to initialize User() ? 可以使用字典作为输入来初始化User()吗? Something like a = User(usr) ? 类似于a = User(usr)吗?

import json                                                            
from sqlalchemy import *                                               
from sqlalchemy.ext.declarative import declarative_base                

engine = create_engine('sqlite:///tutorial.db', echo=True)             

Base = declarative_base()                                              

class User(Base):                                                      
    __tablename__ = 'users'                                            

    id = Column(Integer, primary_key=True)                             
    bbs_id = Column(String)                                            
    name = Column(String)                                              
    sex = Column(String, nullable=False)                               
    city = Column(String)                                              
    state = Column(String)                                             
    class_type = Column(String, nullable=False)                        
    class_id = Column(String, nullable=False)                          
    latitude = Column(Float)                                           
    longitude = Column(Float)                                          

    def __repr__(self):                                                
        return "<User(bbs_id='%s', name='%s'>" % (self.bbs_id, self.name)

Base.metadata.create_all(engine)                                       


with open('mydata.json') as fin:                                        
    usrs = json.load(fin)                                              

usr = usrs[0]                                                          

a = User(id=usr['id'], bbs_id=usr['bbs_id'], name=usr['name'])  

If you know the property names in the JSON object match the column names of the Python model, you can just change: 如果您知道JSON对象中的属性名称与Python模型的列名称匹配,则可以更改:

a = User(id=usr['id'], bbs_id=usr['bbs_id'], name=usr['name'])

to: 至:

a = User(**usr)

Double-star/ dict unpacking passes each key/value pair of the dict as if it were an argument being passed by keyword. 双星/ dict拆包经过每个键/值对的的dict就好像它是由关键字被传递的参数。 Since you didn't override __init__ for your model, it already allows and expects the arguments to be optional and passed by keyword, so this lines up perfectly. 由于您没有为模型覆盖__init__ ,因此它已经允许并且期望参数是可选的并通过关键字传递,因此这很完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM