SqlAlchemy中的动态表创建和ORM映射 [英] Dynamic Table Creation and ORM mapping in SqlAlchemy

查看:315
本文介绍了SqlAlchemy中的动态表创建和ORM映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用关系数据库还很陌生,所以我更喜欢使用一个好的ORM来简化事情。我花时间评估了不同的Python ORM,我认为我需要SQLAlchemy。但是,我已经陷入了精神上的死胡同。

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.

我需要创建一个新表来与我在应用程序的播放器表中创建的播放器的每个实例一起使用。我想我知道如何通过元数据通过更改表的名称然后调用create函数来创建表,但是我不知道如何将其映射到新的动态类。

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?

注意:如果我要问的内容更容易实现,我愿意接受其他ORM的介绍,只是告诉我如何:-)

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

推荐答案

我们被SQLAlchemy宠坏了。

以下内容直接取自教程

,它真的很容易设置和使用。

We are spoiled by SQLAlchemy.
What follows below is taken directly from the tutorial,
and is really easy to setup and get working.

并且因为它经常这样做,

文档在2011年8月移至完整声明式

And because it is done so often,
the documentation moved to full declarative in Aug 2011.

设置您的环境(我正在使用SQLite内存数据库进行测试):

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()

定义表格:

>>> players_table = Table('players', metadata,
...   Column('id', Integer, primary_key=True),
...   Column('name', String),
...   Column('score', Integer)
... )
>>> metadata.create_all(engine) # create the table

如果打开了日志记录,则会看到SQLAlchemy

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

定义班级:

>>> class Player(object):
...     def __init__(self, name, score):
...         self.name = name
...         self.score = score
...
...     def __repr__(self):
...        return "<Player('%s','%s')>" % (self.name, self.score)

将类映射到表:

>>> from sqlalchemy.orm import mapper
>>> mapper(Player, players_table) 
<Mapper at 0x...; Player>

创建玩家:

>>> a_player = Player('monty', 0)
>>> a_player.name
'monty'
>>> a_player.score
0

就是这样,您现在有了一个玩家表。

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

这篇关于SqlAlchemy中的动态表创建和ORM映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆