sqlalchemy multiple foreign keys to same table

2024/10/3 17:12:10

I have a postgres database that looks something like this:

      Table "public.entities"Column     |            Type             |                   Modifiers                    
---------------+-----------------------------+------------------------------------------------id            | bigint                      | not null default nextval('guid_seq'::regclass)type_id       | smallint                    | not nullname          | character varying           | 
Indexes:"entities_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:"entities_parent_id_fkey" FOREIGN KEY (parent_id) REFERENCES entities(id)"entities_type_id_fkey" FOREIGN KEY (type_id) REFERENCES entity_types(id)
Referenced by:TABLE "posts" CONSTRAINT "posts_id_fkey" FOREIGN KEY (id) REFERENCES entities(id)TABLE "posts" CONSTRAINT "posts_subject_1_fkey" FOREIGN KEY (subject_1) REFERENCES entities(id)TABLE "posts" CONSTRAINT "posts_subject_2_fkey" FOREIGN KEY (subject_2) REFERENCES entities(id)Table "public.posts"Column   |  Type  | Modifiers 
-----------+--------+-----------id        | bigint | not nullposter_id | bigint | subject_1 | bigint | not null subject_2 | bigint | not null 
Indexes:"posts_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:"posts_id_fkey" FOREIGN KEY (id) REFERENCES entities(id)"posts_poster_id_fkey" FOREIGN KEY (poster_id) REFERENCES users(id)"posts_subject_1_fkey" FOREIGN KEY (subject_1) REFERENCES entities(id)"posts_subject_2_fkey" FOREIGN KEY (subject_2) REFERENCES entities(id)

I'm trying to figure out how to define the orm object for "posts" to include all 3 of the foreign keys. Notice only id is a primary key. The others are just relationships between posts and entities that are not to be pk'd.

class PostModel(EntitiesModel):__tablename__ = 'posts'id = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), primary_key=True, nullable=False)poster_id = db.Column(db.BigInteger, db.ForeignKey(UserModel.id), nullable=False)subject_1 = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)subject_2 = db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)

I've tried fiddling with it a bit, and besides disabling the foreign keys on subject_1 I can't seem to come up with a solution that doesn't result in this error:

AmbiguousForeignKeysError: Can't determine join between 'entities' and 'posts'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

Any thoughts?

Answer

It's not completely clear what exactly is causing the problem since you omitted the most important part -- code that throws that exception but if adding relationship properties to class PostModel throws that try to add foreign_keys parameter to relationship call as the following:

class PostModel(...):# ...subject1_id = Column(db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)subject2_id = Column(db.Column(db.BigInteger, db.ForeignKey(EntitiesModel.id), nullable=False)subject1 = relationship(EntitiesModel, foreign_keys=subject1_id)subject2 = relationship(EntitiesModel, foreign_keys=subject2_id)
https://en.xdnf.cn/q/70710.html

Related Q&A

Django - Return a file from Root folder via a URL

I purchased a SSL cert online and now ind the mid of verifying my host. How it works is:It gives me a file I have to make that file accessible through a specific URL on my host. If the content of the f…

Flask deployement on lighttpd and raspberry pi

Im trying to deploy a hello flask app to a raspberry pi using lighttpd fastCGI.I followed the instructions on the http://flask.pocoo.org/docs/0.10/deploying/fastcgi/ to the best of my abilityHere is my…

Django admin asks for login after every click

Im working on a Django app hosted on Heroku. Im able to login to the admin with my username, password. But on every single click (or on each click after a few seconds) it redirects me to the login page…

Change numerical Data to Categorical Data - Pandas [duplicate]

This question already has answers here:How to create new values in a pandas dataframe column based on values from another column(2 answers)Closed 6 years ago.I have a pandas dataframe which has a numer…

Why is dataclasses.astuple returning a deepcopy of class attributes?

In the code below the astuple function is carrying out a deep copy of a class attribute of the dataclass. Why is it not producing the same result as the function my_tuple? import copy import dataclass…

customize dateutil.parser century inference logic

I am working on old text files with 2-digit years where the default century logic in dateutil.parser doesnt seem to work well. For example, the attack on Pearl Harbor was not on dparser.parse("12…

How can I check a Python unicode string to see that it *actually* is proper Unicode?

So I have this page:http://hub.iis.sinica.edu.tw/cytoHubba/Apparently its all kinds of messed up, as it gets decoded properly but when I try to save it in postgres I get:DatabaseError: invalid byte seq…

Test assertions for tuples with floats

I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other …

Django: Assigning ForeignKey - Unable to get repr for class

I ask this question here because, in my searches, this error has been generally related to queries rather than ForeignKey assignment.The error I am getting occurs in a method of a model. Here is the co…

Counting day-of-week-hour pairs between two dates

Consider the following list of day-of-week-hour pairs in 24H format:{Mon: [9,23],Thu: [12, 13, 14],Tue: [11, 12, 14],Wed: [11, 12, 13, 14]Fri: [13],Sat: [],Sun: [], }and two time points, e.g.:Start:dat…