Search code examples
pythondjangoself-reference

Django: Query self referencing objects with no child elements


I have the following django model:

class Category(models.Model):
    name = models.CharField(maxlength=20)
    parent = models.ForeignKey('self', null=True)

Note that the field parent is self referencing i.e. a category can have a parent.

How can I find all Category objects that have no child categories?


Solution

  • You can use isnull with the related_query_name:

    class Category(models.Model):
        # ...
        parent = models.ForeignKey('self', null=True, related_name='children', related_query_name='child')
    
    Category.objects.filter(child__isnull=True)
    

    Here, I would recommend to specify at least a meaningful related_name! If you specify only a related_name, the related_query_name defaults to that name (here: children). If you specify none of the two, the rqn defaults to the model name: category, not category_set

    Category.objects.filter(category__isnull=True)  # not so informative