Coverage for src/products/serializers/review.py: 47%

34 statements  

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

1""" 

2This module contains the serializer for product reviews. 

3 

4It provides: 

5- Serialization of review fields, including user info and photo URL 

6- Logic to display the user's full name and profile photo 

7- Validation for review comments and ratings 

8- Used to serialize and validate review data for product APIs 

9""" 

10 

11from django.contrib.contenttypes.models import ContentType 

12 

13from rest_framework import serializers 

14 

15from cloudinary.utils import cloudinary_url 

16 

17from src.products.models.review import Review 

18 

19 

20class ReviewSerializer(serializers.ModelSerializer): 

21 photo_url = serializers.SerializerMethodField() 

22 user_full_name = serializers.SerializerMethodField() 

23 content_type = serializers.SlugRelatedField( 

24 slug_field='model', 

25 queryset=ContentType.objects.all(), 

26 ) 

27 

28 class Meta: 

29 model = Review 

30 fields = [ 

31 'id', 

32 'user', 

33 'rating', 

34 'comment', 

35 'created_at', 

36 'content_type', 

37 'object_id', 

38 'photo_url', 

39 'user_full_name', 

40 'approved', 

41 ] 

42 read_only_fields = [ 

43 'user', 

44 'created_at', 

45 'photo_url', 

46 'user_full_name', 

47 'approved', 

48 ] 

49 

50 def get_photo_url(self, obj): 

51 try: 

52 if obj.user.userphoto.photo: 

53 return cloudinary_url(obj.user.userphoto.photo.public_id)[0] 

54 

55 except Exception: 

56 pass 

57 

58 return None 

59 

60 def get_user_full_name(self, obj): 

61 try: 

62 if ( 

63 obj.user.userprofile.first_name 

64 and obj.user.userprofile.last_name 

65 ): 

66 return f'{obj.user.userprofile.first_name} {obj.user.userprofile.last_name}' 

67 

68 except Exception: 

69 pass 

70 

71 return obj.user.username 

72 

73 def validate_comment(self, value): 

74 if not value or not value.strip(): 

75 raise serializers.ValidationError('Comment is required.') 

76 

77 return value.strip() 

78 

79 def validate_rating(self, value): 

80 if value < 1 or value > 5: 

81 raise serializers.ValidationError( 

82 'Rating must be between 1 and 5.' 

83 ) 

84 

85 return value