python动态生成数据库表 orm,SqlAlchemy中的动态表创建和ORM映射

I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.

I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class.

Can someone give me some tips to help me get past my brain freeze? Is this even possible?

Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)

解决方案

We are spoiled by SQLAlchemy.

What follows below is taken directly from the tutorial,

and is really easy to setup and get working.

And because it is done so often,

the documentation moved to full declarative in Aug 2011.

Setup your environment (I'm using the SQLite in-memory db to test):

>>> from sqlalchemy import create_engine

>>> engine = create_engine('sqlite:///:memory:', echo=True)

>>> from sqlalchemy import Table, Column, Integer, String, MetaData

>>> metadata = MetaData()

Define your table:

>>> players_table = Table('players', metadata,

... Column('id', Integer, primary_key=True),

... Column('name', String),

... Column('score', Integer)

... )

>>> metadata.create_all(engine) # create the table

If you have logging turned on, you'll see the SQL that SQLAlchemy creates for you.

Define your class:

>>> class Player(object):

... def __init__(self, name, score):

... self.name = name

... self.score = score

...

... def __repr__(self):

... return "" % (self.name, self.score)

Map the class to your table:

>>> from sqlalchemy.orm import mapper

>>> mapper(Player, players_table)

Create a player:

>>> a_player = Player('monty', 0)

>>> a_player.name

'monty'

>>> a_player.score

0

That's it, you now have a your player table.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值