如何在某处获取或存盘 EmployeeSerializer 的资料,以便我可以再次使用它来获取活动成员的数量,而不是进行新的数据库呼叫来获取活动成员的数量?
class ProjectSerailizer(serializers.ModelSerializer):
members = EmployeeSerializer(many=True)#returns all members of a project
active_members_count = serializers.SerializerMethodField()# get count of members which are having status active
class Meta:
model = Project
fields = ('id','name','members','active_members_count')
def get_active_members_count(self,obj):
#How can I omit this extra db call? as i am already having data in members variable from EmployeeSerializer, can i loop over members variable somehow and count the active ones?
count = obj.members.filter(status='Active').count()
return count
uj5u.com热心网友回复:
您可以在视图中使用select_related()
和过滤设定查询集annotate()
django.db.models import Count, Q
queryset = Project.objects.select_related('members').annotate(
active_members_count = Count('members', filter=Q(members__status = 'Active'))
)
然后您将获得active_members_count
和其他members
栏位ProjectSerailizer
而无需额外的数据库呼叫
0 评论