4

I have sqlalchemy model which represents a 'post' a user has made

class Post(Base):
    id = Column(Integer, primary_key=True)
    caption = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey("instagram_user.id"))

    user = relationship("User")
    likes = relationship("Like")

I want to be able to know if the post has been liked by a user so I add a hybrid_method:

@hybrid_method
def is_liked_by(self, user):
    return any(like.user_id == user.id for like in self.likes)

I can now get if a post has been liked by a specific user which is fine:

post = db.query(Post).filter(Post.user_id == user.id).one()
post.is_liked_by(user) # True / False

However, I would like the is_liked_by to be stored as an attribute property on the orm object as so:

@hybrid_property
def has_liked(self, user)
    return any(like.user_id == user.id for like in self.likes)

So then I can do something like this:

post = db.query(Post).filter(Post.user_id == user.id)
         .bindparams({'user': user}) # this gets passed to the hybrid property above
         .one()

post.has_liked # True / False

The context of wanting to do this is so I can easily convert to a pydantic model including all the hybrid fields

class PostRead(BaseModel):
    id: int
    caption: str
    user: UserRead
    has_liked: bool


pydantic_post = PostRead.from_orm(post)
pydantic_post.has_liked # True / False

So is there any way to replicate the functionality shown above in sqlalchemy? I basically want to pass through some context when making the query for a post, in this case being the viewing user so I can get whether they have liked the post or not.

shadowByte
  • 93
  • 1
  • 1
  • 6

0 Answers0