Django:查询没有子元素的自引用对象

时间:2022-04-07 00:13:28

I have the following django model:

我有以下django模型:

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?

如何找到没有子类别的所有Category对象?

1 个解决方案

#1


6  

You can use isnull with the related_query_name:

您可以将isnull与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

在这里,我建议至少指定一个有意义的related_name!如果仅指定related_name,则related_query_name默认为该名称(此处为:children)。如果不指定两者,则rqn默认为模型名称:category,而不是category_set

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

#1


6  

You can use isnull with the related_query_name:

您可以将isnull与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

在这里,我建议至少指定一个有意义的related_name!如果仅指定related_name,则related_query_name默认为该名称(此处为:children)。如果不指定两者,则rqn默认为模型名称:category,而不是category_set

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