Search code examples
djangopython-3.xdjango-querysetdjango-1.7

Django Queryset filter checks if related objects exist


I'm trying to create a custom manager which return all Foo instances that dont have Bar attached to them.

# models.py
class Foo(models.Model):
    ...

class Bar(models.Model):
    foo = models.OneToOneField(Foo)
    ...

# managers.py
class FooQueryset(BaseQueryset):
    def no_bar(self):
        return ???

class FooManager(BaseManager):
    def get_queryset(self):
        return EcheanceQueryset(self.model, using=self._db)

    def no_bar(self):
        return self.get_queryset().no_bar()

I'm asking for help with the queryset to get the desired result


Solution

  • try with

    class FooManager(BaseManager):
    
        def no_bar(self):
            return self.get_queryset().filter(bar__isnull=True)