question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error when using Relationships with one-to-one models

See original GitHub issue

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

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
br-allstreetcommented, Oct 18, 2021

Indeed, I was able to work around the issue by setting the relevant fields using the SQLAlchemy conventions, instead of SQLModel:

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", back_populates="user", uselist=False
        ),
    )

class ContactInfo(ContactInfoBase, table=True):
    user_id: uuid.UUID = Field(
        sa_column=Column("user_id", ForeignKey("users.id"), nullable=False)
    )
    user: User = Relationship(
        sa_relationship=RelationshipProperty("User", back_populates="contact_info")
    )

2reactions
arkryoniacommented, Oct 20, 2021

Indeed, I was able to work around the issue by setting the relevant fields using the SQLAlchemy conventions, instead of SQLModel:

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", back_populates="user", uselist=False
        ),
    )

class ContactInfo(ContactInfoBase, table=True):
    user_id: uuid.UUID = Field(
        sa_column=Column("user_id", ForeignKey("users.id"), nullable=False)
    )
    user: User = Relationship(
        sa_relationship=RelationshipProperty("User", back_populates="contact_info")
    )

It works! Good Job @brapaport !

Read more comments on GitHub >

github_iconTop Results From Across the Web

Saving Django Model with OneToOne Relationship Field ...
When i try to save model b i get "Model B : Object has no attribute 'id' " error. How to resolve this...
Read more >
Where is the error when set one to one relationship
i have tow class when set new relation one to one ... Models.The_Sponsor'. The Name value should be a valid navigation property name....
Read more >
One-to-one relationships - Django documentation
To define a one-to-one relationship, use OneToOneField . In this example, a Place optionally can be a Restaurant : from django.db import models...
Read more >
Relationships between tables in a Data Model
A relationship is a connection between two tables of data, ... a database that you import might represent order data by using three...
Read more >
Relations (Reference) - Prisma
A relation is a connection between two models in the Prisma schema. ... In SQL, you use a foreign key to create a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found