Django REST API仅填充从多个字段到多个字段的选定字段

时间:2017-12-13 10:20:50

标签: python django rest django-rest-framework

我的项目中有一个工作API看起来像这样:

{    
    "id": 1,
        "project_name": "Project A",
        "user": [
            {
                "id": 3,
                "employee_id": "001",
                "official_name": "RAY PAlMER",
                "nick_name": "RAY",
                "date_of_birth": "1965-08-25",
                "gender": "1",
                "race": "CAUCASIAN",
                "food_pref": "Vegetarian",
           },
           {
                    "id": 3,
                    "employee_id": "002",
                    "official_name": "LAIRA OMOTO",
                    "nick_name": "LAIRA",
                    "date_of_birth": "1990-01-15",
                    "gender": "2",
                    "race": "WHITE",
                    "food_pref": "Any",
          }
        ]
}

user字段是一个外键字段,它从名为Employee的源模型填充所有内容。我的问题是如何只使用user模型中的几个字段填充Employee多对多字段。例如,我只想填充用户ID,官方名称和性别,因此输出应该是这样的

{    
    "id": 1,
        "project_name": "Project A",
        "user": [
            {
                "id": 3,
                "official_name": "RAY PAlMER",
                "gender": "1",
           },
           {
                    "id": 4,
                    "official_name": "LAIRA",
                    "gender": "2",
           }
        ]
}

以下是我的源代码:

项目模型:

class Project(models.Model):
    user = models.ManyToManyField(Employee, blank=True)

员工模型:

class Employee(models.Model):
    official_name = models.CharField(max_length=200, null=True, blank=True)
    gender_choice = (
                    ('male', 'Male'),
                    ('female', 'Female')
                    )
    gender = models.CharField(max_length=10, choices=gender_choice,  null=True, 
    blank=True)

Serializer:

    class MarketingReportSerializer(serializers.ModelSerializer):
        class Meta:
            model = Project
            fields = ('id', 'project_name','user')
            depth = 1

非常感谢任何帮助!

API:

    class MarketingReportAPI(APIView):
        def get(self, request):
            all_projects = Project.objects.all()
            project_serializer = MarketingReportSerializer(all_projects, many=True)
            return Response(project_serializer.data)

1 个答案:

答案 0 :(得分:3)

创建EmployeeSerializer序列化程序。

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ('id', 'official_name', 'gender')

现在在MarketingReportSerializer

中使用它
class MarketingReportSerializer(serializers.ModelSerializer):
    user = EmployeeSerializer(many=True)

    class Meta:
        model = Project
        fields = ('id', 'project_name', 'user')

然后您可以在视图中使用MarketingReportSerializer