Django REST:无法添加(写入)嵌套项

时间:2013-11-27 03:16:08

标签: django django-rest-framework

我正在尝试使用Django REST Framework(2.3.9)发布嵌套关系,但我收到此错误:

  

ValueError:无法添加“”:实例在数据库“default”上,值在数据库“None”上

似乎Django(1.6)没有意识到我的HeartbeatSerializerItemSerializer了解任何事情

{
    "username":"testing",
    "heartbeat": {
        "items": [
            {
                "item_date": "2013-11-24T05:08:12Z", 
                "item_title": "disagreeing post", 
                "item_type": "post", 
                "item_karma": 25
            }
        ]
    }
}

这是serializers.py:

class ItemSerializer(serializers.ModelSerializer):
    '''
        Item Serializer

        Items are User-generated Content which are captured 
        from various APIs made available from the Web or 
        Internet via REST consumed endpoints or Websites 
        which have been scraped.
    '''

    class Meta:
        model = Item
        # fields = ('id', 'item_title', 'item_karma',
        #           'item_type', 'item_date', )


class DepthPatchSerializer(serializers.ModelSerializer):
    def __init__(self, model=None, **kwargs):
        if model is not None:
            self.Meta.model = model
        super(DepthPatchSerializer, self).__init__(**kwargs);
    def get_nested_field(self, model_field):
        return DepthPatchSerializer(model=model_field.rel.to)


class HeartbeatSerializer(DepthPatchSerializer):
    '''
        Heartbeat Serializer

        Items are User-generated Content (USG) containers which are used
        to consolidate normalized User-generated Interactions (USI).
    '''

    # items_queryset = Item.objects.all()
    # items = ItemSerializer(items_queryset, many=True)

    class Meta:
        model = Heartbeat
        # fields = ('id', 'items', )
        depth = 1


class HackerAddSerializer(serializers.ModelSerializer):
    '''
        User Serializer

        Each User is stored in the system itself for analysis and signaling.

        We store users such that subsets of user behavior through USG can be
        generated and analyzed.
    '''

    heartbeat = HeartbeatSerializer()

    def _save_heartbeat_data(self):
        heartbeat_data = self.init_data.get('heartbeat', None)
        if heartbeat_data:
            hs = HeartbeatSerializer(instance=self.object.heartbeat,
                                    data=heartbeat_data)
            import pdb; pdb.set_trace()  # XXX BREAKPOINT
            if hs.is_valid():
                self.object.heartbeat = hs.object
                hs.save()
            else:
                raise Exception(hs.errors)

    def save(self):
        self._save_heartbeat_data()

        password = self.init_data.get('password', None)
        confirm = self.init_data.get('confirm', None)
        if password and password == confirm:
            self.object.set_password(password)

        super(HackerAddSerializer, self).save()
        return self.object

    class Meta:
        model = Hacker
        exclude = ['last_login', 'password',
                'is_superuser', 'is_staff',
                'is_active', 'user_permissions',
                'groups', ]

2 个答案:

答案 0 :(得分:3)

嵌套序列化程序目前是Readonly(开箱即用)。您必须编写自己的转换方法以支持可写嵌套序列化程序(see docs)。

在django rest框架项目中实现可写嵌套序列化器的工作。

相反,我建议您使用RelatedField(如PrimaryKeyRelatedFieldHyperlinkedRelatedField)来引用嵌套模型。在将数据序列化到客户端时,可以使用depth选项嵌套这些相关字段。

答案 1 :(得分:1)

看看我在类似帖子上写的这个答案:

Similar post answered

希望它会帮助你。