Skip to content

Error when using Relationships with one-to-one models #132

@br-follow

Description

@br-follow

First 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

class User(UserBase, table=True):
    __tablename__ = "users"

    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True,
        index=True,
        nullable=False,
    )

    contact_info: Optional["ContactInfo"] = Relationship(
        sa_relationship=RelationshipProperty(
            "ContactInfo", uselist=False, back_populates="user"
        ),
    )

class ContactInfo(ContactInfoBase, table=True):
    __tablename__ = "contact_info"

    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True,
        index=True,
        nullable=False,
    )

    # Connect to users table
    user_id: uuid.UUID = Field(default=None, foreign_key="users.id")
    user: User = Relationship(back_populates="contact_info")

class Repository:
    def __init__(self, *, user_repository: UserRepository = Depends()):
        self.user_repository = user_repository

    def create_contact_info(
        self,
        *,
        session: Session,
        contact_info_create: ContactInfoCreate,
        user: User,
    ) -> ContactInfo:
        db_contact_info = ContactInfo.from_orm(contact_info_create)
        db_contact_info.user = user

        session.add(db_contact_info)
        session.commit()
        session.refresh(db_contact_info)
        return db_contact_info

Description

An exception is raised when trying to set the user field on the ContactInfo.

I have attempted to follow the instructions from sqlalchemy about one-to-one, though there is no documentation on that kind of relationship from SQLModel.

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 86, in __call__
    await self.simple_response(scope, receive, send, request_headers=headers)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 142, in simple_response
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 52, in app
    response = await func(request)
  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 226, in app
    raw_response = await run_endpoint_function(
  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 161, in run_endpoint_function
    return await run_in_threadpool(dependant.call, **values)
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 40, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/app/./app/api/routes/kyc.py", line 43, in create_contact_info
    kyc_repository.create_contact_info(
  File "/app/./app/api/repositories/kyc_repository.py", line 28, in create_contact_info
    db_contact_info.user = user
  File "/usr/local/lib/python3.9/site-packages/sqlmodel/main.py", line 516, in __setattr__
    set_attribute(self, name, value)
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 2240, in set_attribute
    state.manager[key].impl.set(state, dict_, value, initiator)
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 1253, in set
    value = self.fire_replace_event(state, dict_, value, old, initiator)
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 1279, in fire_replace_event
    value = fn(
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py", line 1714, in emit_backref_from_scalar_set_event
    instance_state(child),
AttributeError: Could not locate column in row for column '_sa_instance_state'

Operating System

macOS

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

3.9.7

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions