Saving Link Model with Extra fields fails
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
# Models
class AssemblyEPDLink(SQLModel, table=True):
assembly_id: Optional[str] = Field(default=None, foreign_key="assembly.id", primary_key=True)
epd_id: Optional[str] = Field(default=None, foreign_key="epd.id", primary_key=True)
conversion_factor: float = 1.0
assembly: "Assembly" = Relationship(back_populates="layer_links")
epd: "EPD" = Relationship(back_populates="assembly_links")
class Assembly(SQLModel, table=True):
"""Assembly database class"""
id: Optional[str] = Field(default_factory=string_uuid, primary_key=True)
name: str = Field(index=True)
category: str
life_time: float = 50
meta_fields: dict = Field(default=dict, sa_column=Column(JSON), nullable=False)
unit: str = "M2"
conversion_factor: float = 1.0
layer_links: List[AssemblyEPDLink] = Relationship(back_populates="assembly")
class EPD(SQLModel, table=True):
"""EPD database class"""
id: Optional[str] = Field(default_factory=string_uuid, primary_key=True)
name: str = Field(index=True)
category: str
gwp_by_phases: dict = Field(default=dict, sa_column=Column(JSON), nullable=False)
version: str
expiration_date: date
date_updated: date
source: str
assembly_links: List[AssemblyEPDLink] = Relationship(back_populates="epd")
# Strawberry Mutation
@strawberry.type
class Mutation:
@strawberry.mutation(permission_classes=[IsAuthenticated])
async def add_assembly(
self,
info: Info,
name: str,
category: str,
life_time: float | None = 50,
meta_fields: Optional[JSON] = None,
layers: Optional[JSON] = None,
conversion_factor: float | None = 1,
) -> GraphQLAssembly:
if meta_fields is None:
meta_fields = {}
session = info.context.get("session")
assembly = Assembly(
name=name,
category=category,
life_time=life_time,
conversion_factor=conversion_factor,
meta_fields=meta_fields,
)
if layers:
query = select(EPD).where(col(EPD.id).in_([layer.get("id") for layer in layers]))
epds = await session.exec(query)
epds = epds.all()
for epd in epds:
link = AssemblyEPDLink(assembly=assembly, epd=epd, conversion_factor=2)
session.add(link)
else:
session.add(assembly)
await session.commit()
await session.refresh(assembly)
return assembly
Description
- I start my test
- Set up a blank database and run
SQLModel.metadata.create_all(bind=engine)
- I create three EPDs and save them to the database
- Then I post a new mutation to create a new Assembly with those EPDs in “layers”
- When I try to commit the AssemblyEPDLink to the session the database throws an error:
'asyncpg.exceptions.NotNullViolationError': null value in column "assembly_id" of relation "assemblyepdlink" violates not-null constraint
Operating System
Linux
Operating System Details
Ubuntu 22.04
SQLModel Version
0.0.6
Python Version
3.10
Additional Context
I have tried to follow the steps outlined in the docs, adapted to my situation, but somehow the link model doesn’t want to save to the database.
When I create an Assembly without a link model everything works fine.
I have a setup with FastAPI, Strawberry, SQLModel and postgres.
Issue Analytics
- State:
- Created a year ago
- Comments:7
Top Results From Across the Web
How to add extra fields to related model before Saving to ...
StackedInline): model = Comment extra = 1 fields = ['comment_text'] formsets ... obj.created_on = timezone.now() if commit: obj.save() return obj.
Read more >Link Model with Extra Fields - SQLModel
Let's say that we want to have an extra field/column to say if a hero is still training in that team or if...
Read more >Error 'bad value for restricted picklist field' appears when a ...
Additional Causes: This error can occur when you deploy a picklist field from sandbox and the values are not selected on the record...
Read more >Adding Extra Fields On Many-To-Many Relationships in Django
If you want to be able to add more information to your many-to-many relationships in Django, this video will show you how to...
Read more >Model field reference - Django documentation
Error message keys include null , blank , invalid , invalid_choice , unique , and unique_for_date . Additional error message keys are specified...
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
@arjunkayalmoni you should just pin the version of sqlalchemy. You can do that by installing sqlalchemy as the right version and Poetry will take care of resolving the dependencies of SQLModel
Thank you @ocni-dtu, yes I done that already with a suggestion by my co-worker, and it indeed worked… thank you again… 😃