Q:

SQLAlchemy retrieve rows with no corresponding objects via foreign key

I've tried a number of variations of this including exists, count/group by and can't seem to get this to work correctly.
I've got the following model:
class Image(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 file_name = db.Column(db.String(128))
 part_id = db.Column(db.Integer, db.ForeignKey('part.id'))

class Part(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 make = db.Column(db.String(128), default='')
 model = db.Column(db.String(128), default='')
 images = db.relationship('Image')

I'm trying to get all Parts that have no images yet. This code didn't work correctly:
p = db.session.query(Part, func.count(Image.id)).join(Image).group_by(Part).having(func.count(Image.id) == 0).all()

A:

You can use any() to test the existence of related rows. For example:
parts = session.query(Part).filter(~Part.images.any())

