I'm using SQLModel, which has SQLAlchemy underneath. I am trying to create a many-to-many relationship using a join table to link the model Paper
back to other Paper
objects via PaperSimilarLink
. It's a "similar papers" function.
class PaperSimilarLink(SQLModel, table=True):
paper_id: Optional[int] = Field(
default=None, foreign_key="paper.id", primary_key=True
)
similar_id: Optional[int] = Field(
default=None, foreign_key="paper.id", primary_key=True
)
class Paper(SQLModel, HasRelatedObjects, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
similar: List["Paper"] = Relationship(
back_populates="similar",
link_model=PaperSimilarLink,
sa_relationship=dict(
primary_join=PaperSimilarLink.paper_id,
secondary_join=PaperSimilarLink.similar_id,
),
)
without adding the primary_join
and secondary_join
to the Paper.similar
column, I get the below error:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship PaperSection.similar - there are multiple foreign key paths linking the tables via secondary table 'papersectionsimilarlink'. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.
After adding it, the code does run but I then get an error trying to access Paper.similar
:
AttributeError: 'Paper' object has no attribute 'similar'
Might be useful to see the postgres table inspection on postgres
----------------+-------------------+-----------+----------+-----------------------------------
figures | json | | |
id | integer | | not null | nextval('paper_id_seq'::regclass)
title | character varying | | not null |
link | character varying | | not null |
pub_date | character varying | | not null |
doi | character varying | | not null |
abstract | character varying | | not null |
pdf_link | character varying | | |
opensummary_id | integer | | |
Indexes:
"paper_pkey" PRIMARY KEY, btree (id)
"paper_doi_key" UNIQUE CONSTRAINT, btree (doi)
Foreign-key constraints:
"paper_opensummary_id_fkey" FOREIGN KEY (opensummary_id) REFERENCES opensummary(id)
...skipping 1 line
TABLE "authorpaperlink" CONSTRAINT "authorpaperlink_paper_id_fkey" FOREIGN KEY (paper_id) REFE
RENCES paper(id)
TABLE "medrivixpaper" CONSTRAINT "medrivixpaper_paper_id_fkey" FOREIGN KEY (paper_id) REFERENC
ES paper(id)
TABLE "paperreferencelink" CONSTRAINT "paperreferencelink_paper_id_fkey" FOREIGN KEY (paper_id
) REFERENCES paper(id)
TABLE "papersection" CONSTRAINT "papersection_paper_id_fkey" FOREIGN KEY (paper_id) REFERENCES
paper(id)
TABLE "papersimilarlink" CONSTRAINT "papersimilarlink_paper_id_fkey" FOREIGN KEY (paper_id) RE
FERENCES paper(id)
TABLE "papersimilarlink" CONSTRAINT "papersimilarlink_similar_id_fkey" FOREIGN KEY (similar_id
) REFERENCES paper(id)