views:

1745

answers:

2

I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?
I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.
Thanks for your help!

+2  A: 

Assuming you are referring to the declarative plugin, where everything I am about to say is documented with examples:

class User(Base):
    __tablename__ = 'users'

    id = Column('id', Integer, primary_key=True)
    addresses = relation("Address", backref="user")

class Address(Base):
    __tablename__ = 'addresses'

    id = Column('id', Integer, primary_key=True)
    user_id = Column('user_id', Integer, ForeignKey('users.id'))
Ali A
So, no way to avoid manually creating foreign keys, junction tables and the like.. :( (aside from using Elixir of course) Thanks!
Joril
No, the relation function can do anything that you can do with SQLA. More powerful than elixir probably.
Ali A
A: 

Look at the "Configuring Relations" section of the Declarative docs. Not quite as high level as "OneToMany" but better than fully specifying the relation.

class Address(Base):
    __tablename__ = 'addresses'

    id = Column(Integer, primary_key=True)
    email = Column(String(50))
    user_id = Column(Integer, ForeignKey('users.id'))
Gregg Lind
Thanks for the updated link :) But.. I'm sorry, I can't see the difference with what Ali A said.. ^^; Given that Address class, you still have to specificy an "address=relation(...)" inside User.. Am I missing something? ^^;
Joril
Ah, I think I misunderstood your question! Yes, to get it both ways, then I think you do have to do that amount of specification. Ask on the SA list (where Mike Bayer answers, settling all disputes!), if you want a more authoritative answer!
Gregg Lind