Home > Software design >  DRF - How to using serializer to load related data
DRF - How to using serializer to load related data

Time:12-11

I have a self related table Employee, and Project table has foreignkey to related to Employee table.

class Employee(models.Model):
    eid = models.CharField(primary_key=True, max_length=10)
    name = models.CharField(max_length=10)
    pmid = models.ForeignKey('self', models.RESTRICT, related_name='team_member', blank=True, null=True,)

class Project(models.Model):
    pid = models.CharField(primary_key=True, max_length=10)
    description = models.CharField(max_length=100)
    teamleaderid = models.ForeignKey(Employee, models.RESTRICT)

and serializers.py

class SubEmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = '__all__'

class EmployeeSerializer(serializers.ModelSerializer):
    team_member = SubEmployeeSerializer(many=True, read_only=True)
    class Meta:
        model = Employee
        fields = '__all__'

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = '__all__'
        depth = 1

views.py

class ProjectList(generics.ListAPIView):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

I hope when request ProjectListView I can get teamleaderid with team_member data but I don't know why team_member not show in my response.

[
    {
        "pid": "p1",
        "description": "p1 project",
        "teamleaderid": {
            "eid": "1",
            "name": "n1",
            "pmid": null,
       ###### how to show below data ###
       #    "team_member": [           #
       #    {                          #
       #         "eid": "5",           # 
       #         "name": "n5",         #
       #         "pmid": "1"           #
       #}                              #
       #################################
        }
    }
]

CodePudding user response:

Try this config,

class EmployeeSerializer(serializers.ModelSerializer):
    team_member = SubEmployeeSerializer(read_only=True, source="pmid")

    class Meta:
        model = Employee
        fields = '__all__'


class ProjectSerializer(serializers.ModelSerializer):
    teamleaderid = EmployeeSerializer(read_only=True)

    class Meta:
        model = Project
        fields = '__all__'
  • Related