1

I'm pretty new to SQLAlchemy (specifically with Flask). I'd like to replicate a subquery that would look like this on Django:

Blah3.objects.filter(id=1, blah2__blah1__attr=1).exists()

where the models look like:

class Blah1(models.Model): ...

class Blah2(models.Model):
    blah1 = models.ForeignKey(Blah1)

class Blah3(models.Model):
    blah2 = models.ForeignKey(Blah2)

So what would that nested subquery in SQLAlchemy look like? I already did:

obj = Blah3.query.filter_by(id=1).one_or_none()
assert obj.blah2.blah1_id == 1

But that requires more queries plus all I really need is do do an EXISTS subquery and really the entire thing should be an EXISTS. Any ideas how to jam pack all this into one query on SQLAlchemy? Thanks!

AOL
  • 31
  • 1
  • 5
  • Ah here you have the models. Assuming you had set up the `relationship` attributes you'd just nest the EXISTS producing expressions: `Blah3.query.filter(Blah3.blah2.has(Blah2.blah1.has(attr=1)))` – Ilja Everilä Jun 03 '21 at 17:57
  • Thank you @IljaEverilä !! – AOL Jun 03 '21 at 18:17
  • The other option would be to use joins: `Blah3.query.join(Blah2).join(Blah1).filter(Blah1.attr == 1)`. – Ilja Everilä Jun 03 '21 at 18:29

0 Answers0