11from django .contrib .auth import get_user_model
2+ from django .contrib .contenttypes .models import ContentType
23from rest_framework import serializers
34
45from core .fields import CustomListField
6+ from core .models import View
57from core .services import get_views_count , get_likes_count , is_fan
68from industries .models import Industry
79from projects .models import Project , Achievement , Collaborator , ProjectNews
@@ -71,6 +73,7 @@ class ProjectDetailSerializer(serializers.ModelSerializer):
7173 short_description = serializers .SerializerMethodField ()
7274 industry_id = serializers .IntegerField (required = False )
7375 likes_count = serializers .SerializerMethodField (method_name = "count_likes" )
76+ views_count = serializers .SerializerMethodField (method_name = "count_views" )
7477 links = serializers .SerializerMethodField ()
7578
7679 @classmethod
@@ -88,6 +91,13 @@ def get_short_description(cls, project):
8891 def count_likes (self , project ):
8992 return LikesOnProject .objects .filter (project = project , is_liked = True ).count ()
9093
94+ def count_views (self , project ):
95+ # FIXME
96+ # TODO: add caching here at least every 5 minutes, otherwise will be heavy load
97+ return View .objects .filter (
98+ content_type = ContentType .objects .get_for_model (Project ), object_id = project .pk
99+ ).count ()
100+
91101 def update (self , instance , validated_data ):
92102 instance = super ().update (instance , validated_data )
93103 instance .save ()
@@ -132,6 +142,14 @@ class ProjectListSerializer(serializers.ModelSerializer):
132142 method_name = "get_collaborator_count"
133143 )
134144 vacancies = ProjectVacancyListSerializer (many = True , read_only = True )
145+ views_count = serializers .SerializerMethodField (method_name = "count_views" )
146+
147+ def count_views (self , project ):
148+ # FIXME
149+ # TODO: add caching here at least every 5 minutes, otherwise will be heavy load
150+ return View .objects .filter (
151+ content_type = ContentType .objects .get_for_model (Project ), object_id = project .pk
152+ ).count ()
135153
136154 short_description = serializers .SerializerMethodField ()
137155
@@ -172,9 +190,7 @@ class Meta:
172190 "views_count" ,
173191 ]
174192
175- read_only_fields = [
176- "leader" ,
177- ]
193+ read_only_fields = ["leader" , "views_count" ]
178194
179195 def is_valid (self , * , raise_exception = False ):
180196 return super ().is_valid (raise_exception = raise_exception )
0 commit comments