Ben2pop
Ben2pop

Reputation: 756

Django Rest Framework, using multiple model queries

I am quite new in using the REST Framework and I did not find in the tutorial how to achieve what I am looking for;

In my serialiser.py I have a class that is used to serialized MyUser models

class MyUserSerializer(ModelSerializer):
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name'
        )

and in my view I am serializing a query that retrieve the user member in a team:

class EmployeeChartData(APIView):
    #import pdb; pdb.set_trace()
    authentication_classes = []
    permission_classes = []
    serializer_class = MyUserSerializer

    def get_serializer_class(self):
        return self.serializer_class

    def get(self, request, format=None, *args, **kwargs):

        team_name_list2 = Project.objects.get(id=kwargs['pk1']).team_id.members.all()
        serializer=self.serializer_class
        team_name_data = serializer(team_name_list2, many=True)
        team_name_data = team_name_data.data

        data = {
        "team_name_list2":team_name_data,
        }

Which give me an output for example:

"team_name_list2": [
        {
            "email": "[email protected]",
            "first_name": "John",
            "last_name": "Doe"
        },

My question is how can I add to that dict custom data and data from other models that are linked to MyUser Model.

For example I have a Team Model

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

How can I add all the team that the specific user is linked to ?

Thx you very much

Upvotes: 0

Views: 1443

Answers (1)

Vaygeth
Vaygeth

Reputation: 184

1- Read about Nested Serializer to give you clean code http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

2- Or Try this:

class MyUserSerializer(ModelSerializer):
    team = serializers.SerializerMethodField()
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name',
            'team',
        )
    def get_team(self, obj):
        print(obj) # for you to understand what's happening
        teams = Team.objects.filter(member=obj)
        serialized_teams = TeamSerializer(teams,many=True)
        return serialized_teams.data

For your Team Serializer as follows

class TeamSerializer(ModelSerializer):
    class Meta:
        model = Team
        fields = (
            'team_name',
            'team_hr_admin',
            'members',  # you can exclude this field since it may seem duplicate
        )

For your view

class EmployeeChartData(viewsets.ModelViewSet):
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer
    permission_classes = []
    http_method_names = ['get',]

Upvotes: 1

Related Questions