将另一个字段添加到另一个模型的REST API中

时间:2017-12-26 09:12:49

标签: python api django-rest-framework

我创建了一个REST API,用于填充Model_A的数据。但现在我需要将另一个数据字段添加到来自另一个模型的API中。如何将parent字段中的ModelParent字段添加到我的API中,parent字段也必须与Model_A项目正确关联,例如下面的示例I'我试图做但不工作(注意:不允许改变model.py ):

API:

class ReportAPI(APIView):
    def get(self, request):
        project_data = []
        all_projects = Model_A.objects.all()
        for project in all_projects:
            project_data.append(project)
            project_parent = ModelParent.objects.filter(project=project.id)
            for parent in project_parent:
                project_data.append(parent)
        project_serializer = SerializerA(all_projects, many=True)
        return Response(project_serializer.data)

其余所需代码:

型号:

class Model_A(models.Model):
    project_name = models.CharField(max_length=50, unique=True)
    project_type = models.CharField(max_length=50, choices=p_type)

class ModelParent(models.Model):
    project = models.ForeignKey('Model_A', on_delete=models.CASCADE, related_name='+')
    parent = models.ForeignKey('ModelParent', on_delete=models.SET(''), related_name='+', null=True, blank=True)

Serializer:

class SerializerA(serializers.ModelSerializer):
    class Meta:
        model = Model_A
        fields = ('id', 'project_name','project_type')
        depth = 1

我的API的当前输出

[
    {
        "id": 1,
        "project_name": "Project A",
        "project_type": "advertisement",
    }
]

期望的输出:

[
    {
        "id": 1,
        "project_name": "Project A",
        "project_type": "advertisement",
        "parent_list": [
                        {
                         id : "1",
                         parent : "Parent 1",
                        },
                        {
                         id : "2",
                         parent : "Parent 2",
                        },
                       ]
    }
]

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

对应模型如下:

class ModelParent(models.Model):
    project = models.ForeignKey('Model_A', on_delete=models.CASCADE, related_name='project')
    parent = models.ForeignKey('ProjectContent', on_delete=models.SET(''), related_name='project_parent', null=True, blank=True)

Serializer如下:

class ModelParentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Model_A
        fields = ('id', 'parent')


class SerializerA(serializers.ModelSerializer):
    parent_list = serializers.SerializerMethodField()

    class Meta:
        model = Model_A
        fields = ('id', 'project_name','project_type', 'parent_list')
        depth = 1

    def get_parent_list(self, obj):
        return ModelParentSerializer(obj.project, many=True).data #project is related name of project field