Django: request standalone object references without 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 parent field is self-relational, i.e. a category may have a parent element.

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

+5
source share
1 answer

You can use isnull with 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 specifying at least a meaningful related_name ! If you specify only related_name , then related_query_name will be assigned this name by default (here: children ). If you do not specify either of the two, the default rqn value matches the model name: category , not category_set

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

Source: https://habr.com/ru/post/1260142/


All Articles