Problem with one-to-one relationship #1433
-
First Check
Commit to Help
Example Codeimport uuid
from datetime import datetime, timezone, date
from typing import Optional
from sqlmodel import Field, SQLModel, Relationship
class User(SQLModel, table=True):
__tablename__ = "users"
user_id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
name: str
email: str
birth_date: date
cpf: str
rg: str
email_verified: datetime | None = None
password: str
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime
doctors: Optional['Doctor'] = Relationship(back_populates='users')
import uuid
from datetime import datetime, timezone
from typing import Optional
from sqlmodel import Field, SQLModel, Relationship
class Doctor(SQLModel, table=True):
__tablename__ = "doctors"
doctor_id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
user_id: uuid.UUID = Field(foreign_key="users.user_id", unique=True)
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime
users: Optional['User'] = Relationship(back_populates="doctors") DescriptionI'm trying to create a table users (parent), and doctors (child), they relationship are one-to-one, a user can be a doctor, but a doctor cant exist without beeing a user, but some how I'm having this erros:
Already searched but can't find any answer. Operating SystemLinux Operating System DetailsLinux Mint 22.01 'Xia' SQLModel Version0.0.24 Python Version3.12.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Found the error. I've had to refactor all my other models, but it worked, I'm sharing the code of my new user and doctor model's so you guys in the future having the same problem can see this:
As I'm new to Python and FastAPI, here is my advice: Always check all of your relationships, this do matter to SQLModel :) |
Beta Was this translation helpful? Give feedback.
Found the error.
The problem was not (only) my user and doctor model, but all the other models depending on them, since they are the main domain of my application, almost everything depend on them.
I've had to refactor all my other models, but it worked, I'm sharing the code of my new user and doctor model's so you guys in the future having the same problem can see this: