'How to get query data converting foreign table's another column
I'm now using sqlalchemy, fastapi develop some REST API. And facing some problem to join multiple tables
I have 2 tables as below
[campaigns]
class Campaign(Base):
__tablename__ = "campaigns"
id = Column(Integer, primary_key=True, unique=True, index=True)
campaign_name = Column(Stirng(100))
category = Column(Integer, ForeignKey('categories.id'))
[categories]
class Category(Base):
__tablename__ = "categories"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(30))
And when I query all the campaigns using db.query(models.Campaign)
, it returns
[
{
"campaign_name": "awesomecampaign_1",
"category": 1,
"id": 2,
},
{
"campaign_name": "awesomecampaign_2",
"category": 1,
"id": 3,
},
{
"campaign_name": "awesomecampaign_3",
"category": 1,
"id": 4,
}
]
But actually I want to get category "name", not just id. like this
[
{
"campaign_name": "awesomecampaign_1",
"category": car,
"id": 2,
},
{
"campaign_name": "awesomecampaign_2",
"category": car,
"id": 3,
},
{
"campaign_name": "awesomecampaign_3",
"category": car,
"id": 4,
}
]
=== What skills did I need to using for join these 2 tables?? Can anybody help this problem?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|