SQLAlchemy: dynamically loaded backlink to another module

Suppose 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 to the user from the Post model in another module. Also, I don't want to "pollute" the user model definition with relationships from this other module.

Is there a cleaner way to do this other than adding a field to the User class from outside the Post model, for example?

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

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

      

thank

+3


source to share


1 answer


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

      

+7


source







All Articles