django m2m字段返回对象而不是键

时间:2018-04-25 19:16:49

标签: django django-rest-framework

我有一个模特:

class Scenario(models.Model):
    tasks = models.ManyToManyField(Task, blank=True)

它的序列化器:

class ScenarioSerializer(serializers.ModelSerializer):

    class Meta:
        model = Scenario
        fields = '__all__'

检索和发布场景的视图:

@api_view(['GET', 'POST'])
def scenarios_list(request):

    scenarios = []

    """
    List all scenarios, or create a new.
    """
    if request.method == 'GET':
        # get projects of a specific stakeholder
        if request.query_params.get('stakeholderId'):
            stakeholderId = request.query_params.get('stakeholderId')
            scenarios = Scenario.objects.filter(stakeholder=stakeholderId)
            serializer = ScenarioSerializer(scenarios, many=True)
            return Response(serializer.data)
        else:
            scenarios = Scenario.objects.all()
            serializer = ScenarioSerializer(scenarios, many=True)
            return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ScenarioSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(stakeholder=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这给我的数据如下:

[{"id":1,"tasks":[1,3]},{"id":2,"tasks":[2,4,5,10]},{"id":3,"tasks":[2,5,6]},{"id":4,"tasks":[2,6,10]}]

我想接收任务对象而不是他们的ID。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您需要TaskSerializer,然后告诉ScenarioSerializer它应该使用嵌套的序列化程序来表示任务。如下所示:

class ScenarioSerializer(serializers.ModelSerializer):
    tasks = TaskSerializer(many=True, read_only=True)
    class Meta:
        model = Scenario
        fields = '__all__'

关于POST数据的说明: 嵌套的序列化程序使用与标准的基于pk的关系完全不同的模式。在编写数据时尤其如此。例如,不清楚嵌套式写入是应该对相关对象使用get_or_create还是仅create。默认情况下,DRF序列化程序不处理嵌套写入。查看the docs以获取有关嵌套关系的详细信息,包括如何处理可写嵌套序列化程序。