Last active
December 17, 2017 16:10
-
-
Save faisalburhanudin/c8d13d64f0060314a4e8954b90c0de60 to your computer and use it in GitHub Desktop.
polymorphic association sqlalchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import event, and_ | |
from sqlalchemy.orm import relationship, foreign, remote, backref | |
class PostFavorites(db.Model): | |
id = db.Column(db.Integer, primary_key=True, nullable=False) | |
user_id = db.Column(db.Integer, nullable=False) | |
post_id = db.Column(db.Integer, nullable=False) | |
post_type = db.Column(db.Integer, nullable=False) | |
@property | |
def post(self): | |
return getattr(self, "parent_%s" % self.post_type) | |
class HasPostFavorite(object): | |
"""HasPostFavorite mixin, creates relationship to post association""" | |
@event.listens_for(HasPostFavorite, "mapper_configured", propagate=True) | |
def setup_listener(mapper, class_): | |
discriminator = class_.type | |
class_.post_favorite = relationship( | |
PostFavorites, | |
primaryjoin=and_( | |
class_.id == foreign(remote(PostFavorites.post_id)), | |
PostFavorites.post_type == discriminator | |
), | |
backref=backref( | |
"parent_%s" % discriminator, | |
primaryjoin=remote(class_.id) == foreign(PostFavorites.post_id) | |
) | |
) | |
@event.listens_for(class_.post_favorite, "append") | |
def append_address(target, value, initiator): | |
value.post_type = discriminator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment