Django REST框架:如何在POST请求中与其他模型关联?

时间:2018-12-08 16:48:18

标签: django django-rest-framework

我对创建API真的很陌生,我可能会误解很多。我想将对象与POST请求中的其他模型相关联,就像我在正常站点中以表单数据形式发布时一样。我该如何使用rest框架?

我的api视图就是这样

@api_view(['GET', 'POST'])
def list_comment(request, pk):
"""
List all comments that belong to an entry or add a comment to the entry
"""
    entry = get_object_or_404(Entry, id=pk)
    comments = Comment.objects.filter(entry=entry)

    if request.method == 'GET':
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CommentSerializer(data=request.data)
        # I want to associate the comment with 'entry' here
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

其余框架页面的form也很难尝试,我想将其更改为表格。我该如何更改?即使选择表单数据,内容表单也不会改变。

1 个答案:

答案 0 :(得分:0)

您可以在序列化器类中使用create方法,并在该类上创建操作,

这是来自www.django-rest-framework.org的示例

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

    def create(self, validated_data):
        return Comment(**validated_data)

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.content = validated_data.get('content', instance.content)
        instance.created = validated_data.get('created', instance.created)
        return instance