Search code examples
djangopostgresqldjango-querysetdjango-q

Complex django query, getting objects whose foreignkey_set does not contain an object that satisfies a restriction


I have a model, foo, and a model bar. bar has a foreignkey to foo, as well as a days field, which is a postgresql DateRangeField

class Foo(models.Model):
    baz = models.CharField()

class bar(models.Model):
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
    days = DateRangeField()

I need to do a query, given a date (day), and a baz: get all Foo objects that satisfy baz = baz, and that do not have an associated bar object that satisfies days.lower < days < days.upper (or in other words, do not have day within the range of their days variable.

I've looked at Q queries, but the only way I've found to do it so far is to get all Foo objects that satisfy baz=baz and then use python to do the rest of it (which is clearly inefficient in terms of DB queries).


Solution

  • I don't fully understand your question, but it seems like you should simply do:

    Foo.objects.filter(baz=baz).exclude(bar__days__contains=day)