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

  • 2
    Creating dynamic tables is a bad idea. Adding a key to a table to distinguish instances of players is a good idea. What are you trying to accomplish with this "dynamic table" business? – S.Lott Jun 10 '09 at 10:56
  • Basically each player get's their own scores table to track their scores over time. A player could be added any point in time, so it would be very hard to track it in a giant scores table with all the players in it...at least to me it does. – Jay Atkinson Jun 10 '09 at 13:36
  • 3
    Of course, the process of asking the question makes me think about it in a whole new light. I probably could create a huge scores table that includes the player's id in a column along with their score info. I could then do a query on the player id to pull in their scores. Thanks everyone. – Jay Atkinson Jun 10 '09 at 13:40
  • 2
    Yes, that (a foreign key to the player ID in the score table) is exactly the right way to do it. You say, "I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things," but you really should take the time to learn how relational database work, even though you're using an ORM, otherwise you'll end up with terrible schema and queries. – Derecho May 26 '10 at 1:11
up vote 21 down vote accepted

We are absolutely 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,
Mike Bayer has made this even easier
with the all-in-one "declarative" method.

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 "<Player('%s','%s')>" % (self.name, self.score)

Map the class to your table:

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

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.
Also, the SqlAlchemy googlegroup is great.
Mike Bayer is very quick to answer questions.

  • 2
    Thanks for the info. Not quite what I was looking for. I was attempting something beyond that, another table per player. – Jay Atkinson Jun 10 '09 at 13:41

Maybe look at SQLSoup, which is layer over SQLAlchemy.

You can also create the tables using plain SQL, and to dynamically map, use these libraries if they already don't have create table function.

Or alternatively create a dynamic class and map it:

tableClass = type(str(table.fullname), (BaseTable.BaseTable,), {})
mapper(tableClass, table)

where BaseTable can be any Python class which you want all your table classes to inherit from, e.g. such Base class may have some utility or common methods, e.g. basic CRUD methods:

class BaseTable(object): pass

Otherwise you need not pass any bases to type(...).

  • Where do I import BaseTable from? I can't find it in sqlalchemy. – Peter Hoffmann Mar 5 '10 at 12:45
  • @Peter Hoffmann, edited answer. – Anurag Uniyal Mar 5 '10 at 14:07
  • Elixir has not been updated since 2009 and seems to have been abandoned. It does not have any support for python 2.7+. – Mike Feb 7 '14 at 15:25

maybe i didn't quite understand what you want, but this recipe create identical column in different __tablename__

class TBase(object):
    """Base class is a 'mixin'.
    Guidelines for declarative mixins is at:

    http://www.sqlalchemy.org/docs/orm/extensions/declarative.html#mixin-classes

    """
    id = Column(Integer, primary_key=True)
    data = Column(String(50))

    def __repr__(self):
        return "%s(data=%r)" % (
            self.__class__.__name__, self.data
        )

class T1Foo(TBase, Base):
    __tablename__ = 't1'

class T2Foo(TBase, Base):
    __tablename__ = 't2'

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

Base.metadata.create_all(engine)

sess = sessionmaker(engine)()

sess.add_all([T1Foo(data='t1'), T1Foo(data='t2'), T2Foo(data='t3'),
         T1Foo(data='t4')])

print sess.query(T1Foo).all()
print sess.query(T2Foo).all()
sess.commit()

info in example sqlalchemy

you can use declarative method for dynamically creating tables in database

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey


Base = declarative_base()

class Language(Base):
    __tablename__ = 'languages'

    id = Column(Integer, primary_key=True)
    name = Column(String(20))
    extension = Column(String(20))

    def __init__(self, name, extension):
        self.name = name
        self.extension = extension

I faced the same problem when I was trying to automate simple CRUD tasks using SQLAlchemy. Here is simple explanation and some code: http://www.devx.com/dbzone/Article/42015

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.