Coverage for src/shopping_bags/serializers.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-08-04 12:59 +0300

1from rest_framework import serializers 

2 

3from src.products.models.inventory import Inventory 

4from src.shopping_bags.models import ShoppingBag 

5from src.common.mixins import InventoryMixin 

6 

7 

8class ShoppingBagSerializer(serializers.ModelSerializer): 

9 """ 

10 Serializer for the ShoppingBag model. 

11 

12 This serializer handles the conversion of ShoppingBag model instances to JSON 

13 and includes additional computed fields for product information and total price. 

14 

15 Key Features: 

16 - Includes product information from the related inventory item 

17 - Calculates total price for each item 

18 - Provides read-only fields for computed values 

19 """ 

20 

21 # inventory = serializers.PrimaryKeyRelatedField(queryset=ShoppingBag._meta.get_field('inventory').related_model.objects.all()) 

22 inventory = serializers.PrimaryKeyRelatedField( 

23 queryset=Inventory.objects.all() 

24 ) 

25 product_info = serializers.SerializerMethodField() 

26 total_price = serializers.SerializerMethodField() 

27 

28 class Meta: 

29 model = ShoppingBag 

30 fields = [ 

31 'id', 

32 'user', 

33 'quantity', 

34 'created_at', 

35 'inventory', 

36 'product_info', 

37 'total_price', 

38 ] 

39 read_only_fields = [ 

40 'id', 

41 'created_at', 

42 'user', 

43 'product_info', 

44 'total_price', 

45 ] 

46 depth = 3 

47 

48 def get_product_info(self, obj): 

49 return InventoryMixin.get_product_info(obj) 

50 

51 def get_total_price(self, obj): 

52 return InventoryMixin.get_total_price_per_product(obj)