Cannot get nested objects when converting to dict
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the SQLModel documentation, with the integrated search.
- I already searched in Google “How to X in SQLModel” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to SQLModel but to Pydantic.
- I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
- I commit to help with one of those options 👆
Example Code
import sqlalchemy as sa
from sqlalchemy import func
from sqlalchemy import orm
from sqlmodel import Field, Relationship, SQLModel
class Address(SQLModel, table=True):
__tablename__ = 'addresses'
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
listing: 'Listing' = Relationship(back_populates='address')
location: 'Location' = Relationship(back_populates='addresses')
class ListingImage(SQLModel, table=True):
__tablename__ = 'listing_images'
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
listing: 'Listing' = Relationship(back_populates='images')
file: str = Field(max_length=255, nullable=False)
listing_id: int = Field(foreign_key='listings.id', nullable=False)
class Listing(SQLModel, table=True):
__tablename__ = 'listings'
created: Optional[datetime] = Field(sa_column_kwargs={'server_default': func.now()}, index=True)
title: str = Field(max_length=100, nullable=False)
price: int = Field(nullable=False)
address_id: int = Field(foreign_key='addresses.id', nullable=True)
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
images: List['ListingImage'] = Relationship(back_populates='listing', sa_relationship_kwargs={'cascade': 'all, delete'})
address: 'Address' = Relationship(back_populates='listing', sa_relationship_kwargs={'cascade': 'all, delete', 'uselist': False})
__mapper_args__ = {"eager_defaults": True}
async def get_multi(
self, db: AsyncSession, *, skip: int = 0, limit: int = 100, order: Any = None, **filters
) -> List[Listing]:
stmt = sa.select(Listing).options(orm.selectinload(Listing.images), orm.selectinload(Listing.address)).filter_by(**filters).order_by(order).offset(skip).limit(limit)
result = await db.scalars(stmt)
return result.all()
##### in some async function ####
data = await get_multi(....)
data[0].address
shows Address(...) object normally
data[0].dict()
{
"id":..
"created":...
"title":...
"price":...
"address_id":...
}
no "images" or "address" nested object after converting to dict
Description
When trying to convert an object using .dict() or .json() the resulting object does not include the nested fields like Address or Images in my example.
I am using SQLAlchemy AsyncSession and doing eager loading of the objects when quering the DB. The nested object shows normally when trying to access it but it doesn’t show up in resulting dict and json object and by contrast not being sent in FastAPI response.
I can confirm this is not the case in Pydantic and models from Pydantic work fine when converted to dict.
Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.8.8
Additional Context
No response
Issue Analytics
- State:
- Created a year ago
- Comments:8 (3 by maintainers)
Top Results From Across the Web
How to convert nested object to nested dictionary in python
I usually do it this way: class Bar: # child class # some init code... def encode(self): return vars(self) class Foo: # parent...
Read more >5 Ways to Convert Dictionary to JSON in Python - FavTutor
To convert the nested dictionary into a json object, you can use the dumps function itself. Here, we have used indent=3, which refers...
Read more >How to convert a nested OrderedDict to dict? - GeeksforGeeks
So, to convert nested OrderedDict to dict, we are using json.loads() and json.dumps() methods. The full form of JSON is JavaScript Object ......
Read more >Nested field type | Elasticsearch Guide [8.5] | Elastic
Internally, nested objects index each object in the array as a separate hidden ... doesn't match because Alice and Smith are not in...
Read more >How to access nested data in Python - Towards Data Science
Sometimes when working with dictionaries you cannot be sure that a key is actually present in the dictionary. Imagine that in the above...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Not sure you will get it working for table models, you’ll probably need models with
table=False
. I tried my own suggestion for data models and it works fine.Thanks for the help here everyone! 👏 🙇
Thanks for reporting back and closing the issue @farahats9 👍