Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Dynamically loaded backreference to another module

Let's suppose that I have a User model in one module.

class User(Model):
    id = Column(Integer, primary_key=True)

Then I want to add a dynamically-loaded, many-to-one relationship towards User from a Post model in another module. Also, I don't want to 'pollute' the User's model definition with relationships from this other module.

Is there a cleaner way of doing this other than adding a field to the User class from outside of the Post model, like this?

class Post(Model):
    user_id = Column(Integer, ForeignKey('user.id'))

User.posts = relationship('Post', backref='user', lazy='dynamic')

Thanks

like image 217
Artur Soler Avatar asked Jan 28 '13 09:01

Artur Soler


1 Answers

Well, you can define it in the Post model (see below)

class Post(Model):
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship('User', backref=backref('posts', lazy='dynamic'))
like image 119
van Avatar answered Nov 05 '22 12:11

van