拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何在DRF中通过单个db呼叫在多个父序列化器变量中使用单个嵌套序列化器的资料?

如何在DRF中通过单个db呼叫在多个父序列化器变量中使用单个嵌套序列化器的资料?

白鹭 - 2022-02-11 2126 0 0

如何在某处获取或存盘 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 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *