New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Relationship from Model Data and inheritance #507
Comments
If you can provide an MRE, I can try to help. 👀 |
it works from typing import List, Optional, ClassVar
from sqlmodel import create_engine, Session, SQLModel, Field, Relationship
engine = create_engine('sqlite://',echo=True)
class SurveyDTO(SQLModel):
...
# other fields..
class ResponsesDTO(SQLModel):
code: int
response: str
class SurveyTable(SurveyDTO, table=True):
__tablename__: ClassVar[str] = 'survey_table'
id: Optional[int] = Field(default=None, primary_key=True)
# how to manage relationship from DTO?
responses: List["ResponsesTable"] = Relationship()
class ResponsesTable(ResponsesDTO, table=True):
__tablename__: ClassVar[str] = 'responses_table'
id: Optional[int] = Field(default=None, primary_key=True)
# how to manage relationship from DTO?
survey_id: Optional[int] = Field(default=None, foreign_key='survey_table.id')
survey: SurveyTable = Relationship()
def main():
with Session(engine) as session:
SQLModel.metadata.create_all(session.connection())
session.commit()
survey = SurveyTable()
response1 = ResponsesTable(code=1, response='test1')
response2 = ResponsesTable(code=1, response='test2')
response3 = ResponsesTable(code=1, response='test3')
survey.responses = [response1, response2, response3]
session.add(survey)
session.commit()
with Session(engine) as session:
survey = session.get(SurveyTable, 1)
print(survey)
if survey is not None:
print(survey.responses)
if __name__ == '__main__':
main() |
This solves the problem from the SQLModel side. From FastAPI side the SurveyDTO and the list come as JSON payload from a POST request.
We could say that the object in the POST request should bea a SurveyTable but in this way I am exposing db data to the outside (and to documentation). If I define the list in SurveyDTO and ovverride in SurveyTable I get Edit: added the additional context with related PR and issue. Thank you guys! |
First Check
Commit to Help
Example Code
Description
I am trying to create a a one to many relationship through inheritance from a model class to a table class.
I don't understand how to create the relationship with the List[ResponsesDTO] in the table without duplicating code.
Maybe I am missing something?
Thank you for your help :)
Operating System
Windows
Operating System Details
No response
SQLModel Version
0.08
Python Version
3.8
Additional Context
Seems related to #18 and #469
The text was updated successfully, but these errors were encountered: