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