2

我有一个使用 django 和tastepie 的服务器以及一个使用backbone.js 的基于Web 的客户端应用程序,我可以正常读取数据,但是当我尝试使用外键添加新模型然后同步时出现问题。

所以我认为最简单的方法是调用自动与服务器同步的 collection.create。如果我在没有外键的表上这样做,它工作正常。但是,当我有一个与服务器数据库有关系的模型时,我不知道我应该如何指定外键。

模型外键最初采用以下格式:/api/v1/porttype/4/

如果我尝试构建这样的字符串,我会收到 404 错误,如果我尝试只发送一个 int,我会收到 404 错误。

我不确定服务器期望什么。我不确定这是否是配置问题......我现在有点迷茫。到目前为止,我做了这样的事情:

collection.create([ { 'project': '/api/v1/porttype/4/', 'name': 'test' } ]);

project在这种情况下将是外键。

编辑:我从服务器返回的堆栈跟踪:

{"error_message": "", "traceback": "Traceback (most recent call last)n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 192, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 397, in dispatch_list\n    return self.dispatch('list', request, **kwargs)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 427, in dispatch\n    response = method(request, **kwargs)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 1165, in post_list\n    updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 1774, in obj_create\n    bundle = self.full_hydrate(bundle)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/resources.py\", line 698, in full_hydrate\n    value = field_object.hydrate(bundle)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/fields.py\", line 636, in hydrate\n    value = super(ToOneField, self).hydrate(bundle)\n\n  File \"/Library/Python/2.7/site-packages/django_tastypie-0.9.11-py2.7.egg/tastypie/fields.py\", line 154, in hydrate\n    elif self.attribute and getattr(bundle.obj, self.attribute, None)n\n  File \"/Library/Python/2.7/site-packages/Django-1.3.2-py2.7.egg/django/db/models/fields/related.py\", line 301, in __get__\n    raise self.field.rel.to.DoesNotExist\n\nDoesNotExist\n"}

似乎它无法识别它......从我搜索这个 django 错误的内容来看,似乎你在添加时没有发送非空字段,但不确定

帮助!

4

1 回答 1

0

为什么不在模型中设置外键,然后在 JSON 有效负载中发送?例如:

不要以这种方式传递引用:

collection.create([ { 'project': '/api/v1/porttype/4/', 'name': 'test'} ]);

相反,您只需将服务器端的请求作为另一个参数处理。

在事情的主干方面,我会将上述内容更改为:

collection.create([ { 'project_id': 4, 'name': 'test'} ]);

其中 project_id 是对项目表的 foreign_key 引用

然后,在您的控制器代码中,您需要让 ORM 处理其余部分。我把它作为练习留给读者:-)

于 2013-01-29T04:51:56.420 回答