Reputation: 6895
I have the following models in sqlalchemy:
class Magazine(db.Model):
id= db.Column(db.Integer, primary_key=True)
name= db.Column(db.String(50))
issues= db.relationship('Issue', backref='magazine', lazy='dynamic')
class Issue(db.Model):
id= db.Column(db.Integer, primary_key=True)
magazine_id= db.Column(db.Integer, db.ForeignKey('magazine.id'))
date= db.Column(db.Date)
Magazines holds names of magazines and issues holds the issues of each magazine. These are weekly magazines, so the date
field in Issue
is the day of the issue.
I am try to build a query to select all magazines who do not have an issue for a specific date. How's the easiest way to do it?
Upvotes: 0
Views: 564
Reputation: 324475
Since this is tagged sql
, I presume you're OK with proper SQL, not whatever SQLAlchemy uses. This should be a hint about how to express the same thing in SQLAlchemy anyway.
SELECT *
FROM magazine m
WHERE NOT EXISTS (
SELECT 1 FROM issue i WHERE i.magazine_id = m.id AND i."date" = $1
);
$1
is the date parameter; in Python it might be %s
or ?
... whatever your language's parameter placeholder is.
BTW, "date"
is a terrible name for a column. It'll have to be double-quoted everywhere because it's a typename and an SQL reserved word.
Upvotes: 1