mptt with count of a different models instances that have tree model as foreignkey

為{幸葍}努か 提交于 2019-12-06 01:40:02

What you want is 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.

For instance in the admin you can use something like that:

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)'

My answer is connected to Django-Oscar, but you may find it out helpful

{{ for tree category in tree_categories }} is a Category class, so it's possible get children by

{{ tree_category.get_num_children }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!