Django Rest Framework,使用多个模型查询

时间:2017-12-06 09:32:22

标签: django django-rest-framework django-views

我是使用REST框架的新手,我在教程中没有找到如何实现我想要的东西;

在我的serialiser.py中,我有一个用于序列化MyUser模型的类

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

在我看来,我正在序列化一个检索团队中用户成员的查询:

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,
        }

例如,它给了我一个输出:

"team_name_list2": [
        {
            "email": "johndoe@gmail.com",
            "first_name": "John",
            "last_name": "Doe"
        },

我的问题是如何添加到该链接到MyUser 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")

如何添加特定用户链接的所有团队?

非常感谢你

1 个答案:

答案 0 :(得分:1)

1-阅读有关嵌套序列化程序的信息,为您提供干净的代码http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

2-或试试这个:

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

您的Team Serializer如下

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

供您查看

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