Nested result for nested serializer in django with many to many fields

i have four models :

  1. CommonAccess model that have four ManyToMany to AccessSubject,AccessGroup,AccessAction and AccessSubGroup
class CommonAccess(TimeStampedModel):
    name = models.CharField(blank=True,null=True,max_length=200,)
    subjects = models.ManyToManyField(AccessSubject,)
    groups = models.ManyToManyField(AccessGroup,blank=True,)
    actions = models.ManyToManyField(AccessAction,blank=True,)
    sub_groups = models.ManyToManyField('AccessSubGroup,blank=True, )

    def __str__(self):
        return self.ename or ''
  1. AccessSubject model:
class AccessSubject():
    name = models.CharField(blank=True, null=True, max_length=200, unique=True,)
  1. AccessGroup model:
class AccessGroup():
    name = models.CharField(blank=True, null=True, max_length=200, unique=True,)
    access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,related_name='access_groups')
  1. AccessSubGroup model:
class AccessSubGroup():
    name = models.CharField(blank=True, null=True, max_length=200, unique=True,)
    access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,)
    access_group = models.ForeignKey(AccessGroup,on_delete=models.SET_NULL,related_name='accessgroup_subgroups')

i need to when pass a commonAccess id get commonAccess with nested subject,group and sub group that fileter with ManyToMany fields in CommonAccess model like :

name: 'sample'
subject: [ name: 'sub1'
           group : [ name: 'gr1'
                     sub_group: [ name: 'sgr1'
                                ]
                                [ name: 'sgr2'
                                ]
                   ]
           group : [ name: 'gr2'
                     sub_group: [name: 'sgr3']
                   ]
         ]
         [ name: 'sub2'
           group : [ name: 'gr3'
                   ]
         ]

i have used serializer like below, but only subjects filtered by CommonAccess ManyToMany fileds, i want Group and SubGroup also filtered by CommonAccess :

class NewCommonAccessSerializer(ModelSerializer):
    subjects = NewAccessSubjectNestedSerializer(read_only=True, many=True)
    class Meta:
        model = CommonAccess
        fields = "__all__"

class NewAccessSubjectNestedSerializer(ModelSerializer):
    accesslevel_groups = NewAccessGroupNestedSerializer(many = True)  
    class Meta:
        model = AccessSubject
        fields = '__all__'

class NewAccessGroupNestedSerializer(ModelSerializer):

    class Meta:
        model = AccessGroup
        fields = '__all__' 
Back to Top