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?
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With