1
\$\begingroup\$

I am using flask with sqlAlchemy to connect with a postgresql database with two tables

Users table (id, name)

Admissions table (id, userId)

Admissions table with a foreign key (userId) connected to Users(id)

I want to get Users if user.id is found in admissions userId

This is what I am doing

users = [i for i in Users.query.all() if Admissions.query.filter_by(userid=i.id).first()]

Any better way to do this?

Thank you

Edit: Users

Table "public.users"
  Column  |         Type          | Collation | Nullable |              Default               
----------+-----------------------+-----------+----------+------------------------------------
 id       | integer               |           | not null | nextval('users__id_seq'::regclass)
 sid      | character varying(10) |           |          | 
 name     | text                  |           |          | 
 username | text                  |           |          | 
 password | text                  |           |          | 
 admin    | boolean               |           |          | false
 deleted  | boolean               |           |          | false
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "admissions" CONSTRAINT "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id)

Admissions

Table "public.admissions"
   Column   |           Type           | Collation | Nullable |                Default                 
------------+--------------------------+-----------+----------+----------------------------------------
 id         | integer                  |           | not null | nextval('admissions_id_seq'::regclass)
 examid     | integer                  |           |          | 
 userid     | integer                  |           |          | 
 startdate  | timestamp with time zone |           |          | CURRENT_TIMESTAMP
 submitdate | timestamp with time zone |           |          | 
Indexes:
    "admissions_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id)
\$\endgroup\$
  • \$\begingroup\$ Could you please add the SQL for the definitions of all 3 tables. \$\endgroup\$ – pacmaninbw Apr 15 at 17:02
  • \$\begingroup\$ @pacmaninbw done \$\endgroup\$ – Hadi Apr 15 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.