使用django-mptt在数据库中查询具有至少一个子类别和至少一种产品的所有根类别

时间:2019-02-26 05:31:28

标签: django django-mptt

我有一个declare @SDate datetime='2009-07-11' declare @EDate datetime='2012-12-30' declare @Sid int declare @Eid int --select * from dbo.SomeDateTable --where StartDate>=@SDate and StartDate<=@EDate Above query give Table Scan select @Sid=min(id) ,@Eid=max(id) from dbo.SomeDateTable where StartDate>=@SDate and StartDate<=@EDate 模型,我使用django-mptt拥有子类别(以及子子类别,等等)。我也有分配给类别的产品。

我想在数据库中查询具有至少一个子类别和至少一种产品的所有根类别。例如,考虑以下数据结构:

select @Sid,@Eid
select id,StartDate,vdata from dbo.SomeDateTable
where id>=@Sid and id<=@Eid

在这种情况下,我希望查询仅返回“垃圾食品”类别,因为它是唯一符合所有三个条件(根类别,至少具有一个子类别,至少具有一种产品)的类别。

我浏览了django-mptt文档,但没有找到一种方法。也许我忽略了它。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以在子类别和产品的“类别”的多对一字段中进行过滤。 所以也许像这样:

<?php
echo json_encode(array('number' => '23589'), JSON_NUMERIC_CHECK);
?>

Category.objects.filter(
    parent=None,  # must be root category
    children__in=Category.objects.filter(level=1),  # must have at least one sub-category
    products__in=Product.objects.all()  # must have at least one product
).distinct()
相关问题