- Sponsor
-
Notifications
You must be signed in to change notification settings - Fork 715
Specifying one-to-many relationships explicitly without foreign keys #359
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
Comments
I got it to work with from typing import List, Optional
from sqlalchemy.orm import RelationshipProperty
from sqlmodel import SQLModel, Field, Relationship
class User(SQLModel, table=True):
id: str = Field(primary_key=True)
orders: Optional[List["Order"]] = Relationship(back_populates="user",
sa_relationship=RelationshipProperty("Order",
primaryjoin="foreign(User.id) == Order.user_id",
uselist=True))
class Order(SQLModel, table=True):
txn_id: str = Field(primary_key=True)
user_id: str = Field()
user: User = Relationship(back_populates="orders",
sa_relationship=RelationshipProperty("User",
primaryjoin="foreign(Order.user_id) == User.id",
uselist=False))
user = User(id="theuserid")
order1 = Order(txn_id="theorderid", user_id=user.id) |
Thanks bro, it saves my day! |
Thank you for this, I spent so long trying to get this to work in SQLModel and this fixed it! |
First Check
Commit to Help
Example Code
Description
I'm using PlanetScale which doesn't support foreign keys and thus wanted to make use of relationships without them.
From reading up the docs and other issues, SQLAlchemy's
primaryjoin
looked to be the solution for this.However, when running
Variant #1
, I get this exception -Post this, I try ditching
User.orders
to at least get theOrder
side working, as shown inVariant #2
, and get this exception -How do I get relationship attributes working for such types of one-to-many relationships without using (db-level) foreign keys?
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.10.4
Additional Context
The SQLAlchemy version is 1.4.35
The text was updated successfully, but these errors were encountered: