From 84fc2785d6d5c9144e39f1342fbd324caff3aa29 Mon Sep 17 00:00:00 2001 From: Oliver Date: Tue, 20 Jul 2021 21:26:51 +1000 Subject: [PATCH] Create a custom Manager class for the Part model - Always perform prefetch_related calls --- InvenTree/part/models.py | 19 +++++++++++++++++++ InvenTree/part/serializers.py | 19 ------------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py index 72d388746b..95a8e407b9 100644 --- a/InvenTree/part/models.py +++ b/InvenTree/part/models.py @@ -284,6 +284,23 @@ def match_part_names(match, threshold=80, reverse=True, compare_length=False): return matches +class PartManager(models.Manager): + """ + Defines a custom object manager for the Part model. + + The main purpose of this manager is to reduce the number of database hits, + as the Part model has a large number of ForeignKey fields! + """ + + def get_queryset(self): + + return super().get_queryset().prefetch_related( + 'category', + 'stock_items', + 'builds', + ) + + @cleanup.ignore class Part(MPTTModel): """ The Part object represents an abstract part, the 'concept' of an actual entity. @@ -321,6 +338,8 @@ class Part(MPTTModel): responsible: User who is responsible for this part (optional) """ + objects = PartManager() + class Meta: verbose_name = _("Part") verbose_name_plural = _("Parts") diff --git a/InvenTree/part/serializers.py b/InvenTree/part/serializers.py index 92dda58590..db543b8602 100644 --- a/InvenTree/part/serializers.py +++ b/InvenTree/part/serializers.py @@ -215,25 +215,6 @@ class PartSerializer(InvenTreeModelSerializer): if category_detail is not True: self.fields.pop('category_detail') - @staticmethod - def prefetch_queryset(queryset): - """ - Prefetch related database tables, - to reduce database hits. - """ - - return queryset.prefetch_related( - 'category', - 'category__parts', - 'category__parent', - 'stock_items', - 'bom_items', - 'builds', - 'supplier_parts', - 'supplier_parts__purchase_order_line_items', - 'supplier_parts__purchase_order_line_items__order', - ) - @staticmethod def annotate_queryset(queryset): """