Marvin Ludwig
Marvin Ludwig

Reputation: 25

SQLAlchemy show relationship unnested

How can i get a relationsship not as a nested object?

When I do this get request:

db.query(self.model).filter(self.model.id == id).first()

I will get this response:

{
  "message": "test",
  "id": 96,
  "user": {
    "name": "test user",
    "avatar":"xxx"
    "id": 5
  }
}

And i need the response in this format:

{
  "message": "test",
  "id": 96,
  "name":"test user"
  "avatar":"xxx"
}

So i have multiple Cards with Comments and i solved it likes this:

for comment in card.comments:
    setattr(comment, "avatar", comment.user.avatar)
    setattr(comment, "name", comment.user.name)

whenever i need the comments, i have to iterate through them

I'm a total beginner in sqlalchemy. Can someone please tell me how to solve this better.

Maybe some parameters which i should use on the Model? Or maybe the response_model Schema?

class KanbanComment(Base):
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("user.id"))
    user = relationship("User")

Upvotes: 1

Views: 86

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123829

If you add a @property to your class you can access that property as a "top level" attribute. For example,

class KanbanComment(Base):
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("user.id"))
    user = relationship("User")

    @property
    def name(self):
        return self.user.name


with Session(engine) as sess:
    a_comment = sess.get(KanbanComment, 96)
    print(repr(a_comment.name))  # 'test user'

Upvotes: 1

Related Questions