gpt4 book ai didi

django - mptt 包含以树模型作为外键的不同模型实例的计数

转载 作者:行者123 更新时间:2023-12-03 07:16:15 27 4
gpt4 key购买 nike

在网上商店中,我使用 django-mptt 来处理多个级别的产品类别。我也有各自属于一个类别的产品。

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

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

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

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

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

最佳答案

你想要的是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)'

关于django - mptt 包含以树模型作为外键的不同模型实例的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35717448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com