【问题标题】:mptt with count of a different models instances that have tree model as foreignkey具有树模型作为外键的不同模型实例的计数的 mptt
【发布时间】:2016-03-01 07:55:14
【问题描述】:

在一家在线商店中,我使用django-mptt 来表示具有多个级别的产品类别。我也有属于一个类别的产品。

现在我想像这样可视化类别树:

all(18)
- edible (10)
-- food (4)
-- drink (6)
- inedible (8)
-- wood (3)
-- rock (5)

其中范围中的数字是每个类别的产品数量。

我能够可视化类别树。我也可以将产品数量放在类别名称后面,但我这样做的方式似乎非常低效。我基本上在类别模型中有一个get_number_of_products() 方法,它返回一个类别的产品数量。但这每次都需要一个新的数据库查询。

解决此问题的一种方法是使用缓存,因为我不经常更改产品计数,但我更喜欢一种需要较少数据库查询来获取包含产品计数的树的方法。

【问题讨论】:

    标签: django django-mptt


    【解决方案1】:

    你想要的是add_related_count

    Category.objects.add_related_count(
       Category.objects.get_descendants(include_self=True),  # Queryset
       Product,  # Related mobile
       'category',  # Name of the foreignkey field
       'count',  # Name of the property added to the collection
        cumulative=True)  # Cumulative or not.
    

    例如,在管理员中,您可以使用类似的东西:

    class CategoryAdmin(DraggableMPTTAdmin):
        mptt_indent_field = "name"
        list_display = ('tree_actions', 'indented_title', 
                        'related_products_count', 'related_products_cumulative_count')
        list_display_links = ('indented_title',)
    
        def get_queryset(self, request):
            qs = super().get_queryset(request)
    
            # Add cumulative product count
            qs = Category.objects.add_related_count(
                    qs,
                    Product,
                    'category',
                    'products_cumulative_count',
                    cumulative=True)
    
            # Add non cumulative recipe count
            qs = Category.objects.add_related_count(qs,
                     Product,
                     'categories',
                     'products_count',
                     cumulative=False)
            return qs
    
        def related_products_count(self, instance):
            return instance.products_count
        related_product_count.short_description = 'Related products (for this specific category)'
    
        def related_products_cumulative_count(self, instance):
            return instance.products_cumulative_count
        related_products_cumulative_count.short_description = 'Related products (in tree)'
    

    【讨论】:

    【解决方案2】:

    我的回答与 Django-Oscar 有关,但您可能会发现它很有帮助

    {{ for tree category in tree_categories }} 是一个 Category 类,所以可以通过

    {{ tree_category.get_num_children }}
    

    【讨论】:

    • 这个或get_descendant_count 会返回当前实例是父级的类别数,但不会返回与该类别关联的实例数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2015-12-04
    相关资源
    最近更新 更多