0

I have a sql code that will print out all events that user with id=3 did not join particular yet:

SELECT * from Event where id not in (select event_id from Participant where user_id =3);

I want to write it in SQLAlchemy and so far I've got this

Event.query.filter(not_(Participant.user_id==3))

but produced query is not what I initially wrote:

SELECT "Event".id AS "Event_id",
"Event".name AS "Event_name",
"Event".published AS "Event_published",
"Event".published_when AS "Event_published_when",
"Event".published_by AS "Event_published_by"
FROM "Event", "Participant"
WHERE "Participant".user_id != ?

The above is not giving any results. I guess I wrote this SQLAlchemy query incorrectly. What is wrong with it?

2 Answers 2

0

Correct syntax:

Event.query.filter(Event.id.notin_(db.session.query(Participant.event_id).filter(Participant.user_id==session['uid'])))

Subquery had to be limited to event_id only. Thanks to this it will now return correct data from DB.

Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this:

sub = Participant.query(Participant.event_id).filter(Participant.user_id==3)
res = Event.query.filter(Event.id.notin_(sub))

or maybe this way:

res = Session.query(Event, Participant).filter(Event.id == Participant.user_id).filter(Participant.user_id == 3)

2 Comments

@SuperShoot yeap! I think you're correct. Thanks for the notice
thanks for your input! Unfortunatelly, both solutions were incorrect due to problems with subquery (returned more than 1 record) so I had to modify it a bit. See my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.