Django:在 values() 查询集中检查 is_null
Django: checking is_null in values() queryset
我有这个查询集:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', number_of_children=Count('children')
)
它完成了工作。但我真的只是用它来检查 object 是否有 children (我真的不关心它有多少)。有没有办法在这里使用isnull
?
我试过:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', 'children__isnull'
)
和:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', is_not_parent='children_isnull'
)
但都不正确。
不完全确定你的 model-relations 是什么,但你可以像这样过滤关系:
Grandparent.objects.filter(parents__children__isnull=True)
这会找到所有没有任何 grandchildren 的 grandparents。
根据您的 grandparents、parents 和 children 之间的关系,您可能需要将 .distinct()
添加到查询集中以避免重复。
这样的事情可能会奏效。
annotate(\
has_children=ExpressionWrapper(Q(children__isnull=False), \
output_field=BooleanField())
)
我有这个查询集:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', number_of_children=Count('children')
)
它完成了工作。但我真的只是用它来检查 object 是否有 children (我真的不关心它有多少)。有没有办法在这里使用isnull
?
我试过:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', 'children__isnull'
)
和:
output = self.filter(parent=task, user=user).values(
'label', 'minutes_allotted', 'days_to_complete', 'pk', is_not_parent='children_isnull'
)
但都不正确。
不完全确定你的 model-relations 是什么,但你可以像这样过滤关系:
Grandparent.objects.filter(parents__children__isnull=True)
这会找到所有没有任何 grandchildren 的 grandparents。
根据您的 grandparents、parents 和 children 之间的关系,您可能需要将 .distinct()
添加到查询集中以避免重复。
这样的事情可能会奏效。
annotate(\
has_children=ExpressionWrapper(Q(children__isnull=False), \
output_field=BooleanField())
)