Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
Frankline Avatar asked Nov 22 '16 13:11

Frankline


1 Answers

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
like image 89
user2390182 Avatar answered Sep 22 '22 01:09

user2390182