Skip to content

Instantly share code, notes, and snippets.

@jdswinbank
Last active December 17, 2015 08:39
Show Gist options
  • Save jdswinbank/5582119 to your computer and use it in GitHub Desktop.
Save jdswinbank/5582119 to your computer and use it in GitHub Desktop.
class Observation(models.Model):
invalid = models.BooleanField(default=False)
class Beam(models.Model):
observation = models.ForeignKey(Observation)
field = models.ForeignKey(Field)
class Field(models.Model):
pass
# The aim: find all Fields for which all Beams belong to invalid Observations.
# This gives the correct answer:
fields = Field.objects.all().annotate(n_beams=Count('beam'))
fields = [f for f in fields if f.beam_set.filter(observation__invalid=True).count() == f.n_beams]
# ...but is woefully inefficient in terms of number of queries -- I see a query along the lines of this:
#
#SELECT COUNT(*) FROM "observationdb_beam"
# INNER JOIN "observationdb_observation"
# ON ("observationdb_beam"."observation_id" = "observationdb_observation"."obsid")
# WHERE ("observationdb_beam"."field_id" = 669
# AND "observationdb_observation"."invalid" = true
#
# for every field. There must be a smarter way!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment