Django rest framework serializer.save()返回“无效数据。预期字典,但得到组”

时间:2017-11-06 12:46:28

标签: python django django-rest-framework

我试图调用serlizerer来保存viewset中的对象 这是views.py

class GroupViewSet(viewsets.ViewSet):
        ....
        @detail_route(methods=['post'], url_path='task')
        def get_task(self, request, pk=None):
            group = get_object_or_404(Group, pk=pk)
            data = {"group": group }
            log_serializer = LogSerializer(data=data)
            if log_serializer.is_valid(raise_exception=True):
                log_serializer.save()

这是serializer.py

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name')

class LogSerializer(serializers.ModelSerializer):
    group = GroupSerializer()
    class Meta:
        model = Log
        fields = ('group', 'created')

这是model.py:

class Group:
....

class Log(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Server) #Not the group of user , it is the group id which user try to query 
    created = models.DateTimeField(auto_now_add=True)

帖子responese;

{
    "group": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got group."
        ]
    }
}

1 个答案:

答案 0 :(得分:2)

根据您的LogSerializer,当您将数据属性传递给序列化程序时,它需要这样的字典:

{
    // note this is a dictionary or a JSON Object.
    // id is omitted because it's auto-inserted natural key
    {
        'name': 'group-name'
    },
    'created': '2017-11-06 20:17:59'
}

但是,您传递了一个组实例,您从此处获取:group = get_object_or_404(Group, pk=pk)因此,当您致电.is_valid时会引发异常。

假设您尝试使用组外键创建一个Log对象,对于现有组,快速黑客将data = {"group": group }替换为data = {"group": group.__dict__ }