0

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

1 Answer 1

1

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',]
Sign up to request clarification or add additional context in comments.

4 Comments

Hi thx for your answer ;) I got the error ("Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = 'all' to the TeamSerializer serializer.",) . any idea ?
@Ben2pop typo in TeamSerializer, change field to fields
Yes I just figured it out :) thx you so much could you explain me why do we need to add : queryset = MyUser.objects.all() and http_method_names = ['get',] ?
On the queryset I used MyUser.objects.all() for I noticed you didn't perform any queryset for your MyUser serializer so my assumption was that you wanted all users records. You can do whatever suits you, for instance MyUser.objects.filter(first_name='John'), or if you want more customization like taking passed parameters from requests you can define & override "def list" or "def retrieve" methods on your EmployeeCharData, in your case to get kwargs['pk1']. as for http_method_names, you can removed or add whatever like ['get','post',] if you want to post data as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.