鉴于这些模型:
class ModelA(models.Model):
# Some fields
# Some relationship
class ModelB(models.Model):
# Some fields
a = models.ForeignKey(ModelA)
还有这些美味的资源:
class ResourceA(ModelResource):
b_list = fields.ToManyField('app.api.ResourceB', 'a_set', null=True, related_name='a')
class ResourceB(ModelResource):
a = fields.ToOneField(ResourceA, 'a', null=True)
如果我访问 ResourceB (/api/v1/resourceA/##/) 的详细端点,我可以看到所有相关 B 的 uri - 反向关系有效。返回的数据如下所示:
{
'b_list': [
'/api/v1/resourceB/1/',
'/api/v1/resourceB/2/',
]
}
如果我尝试 PUT 或 PATCH 资源 A 以向其添加新 B,请使用以下数据说:
{
'b_list': [
'/api/v1/resourceB/1/',
'/api/v1/resourceB/2/',
'/api/v1/resourceB/3/',
]
}
我收到错误:'ManyRelatedManager' object has no attribute 'add'
使用此堆栈跟踪:
Traceback (most recent call last):
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 202, in wrapper
response = callback(request, *args, **kwargs)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 449, in dispatch_detail
return self.dispatch('detail', request, **kwargs)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 472, in dispatch
response = method(request, **kwargs)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1611, in patch_detail
self.update_in_place(request, bundle, deserialized)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 1634, in update_in_place
return self.obj_update(bundle=original_bundle, **kwargs)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2166, in obj_update
return self.save(bundle, skip_errors=skip_errors)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2257, in save
self.save_m2m(m2m_bundle)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2382, in save_m2m
related_resource.save(updated_related_bundle)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2257, in save
self.save_m2m(m2m_bundle)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2382, in save_m2m
related_resource.save(updated_related_bundle)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2257, in save
self.save_m2m(m2m_bundle)
File \"/home/username/.virtualenvs/myapp/local/lib/python2.7/site-packages/tastypie/resources.py\", line 2385, in save_m2m
related_mngr.add(*related_objs)
AttributeError: 'ManyRelatedManager' object has no attribute 'add'
如果我随后立即PUT/PATCH 相同的数据,则不会出现错误,也不会出现堆栈跟踪,并且该项目已成功添加到关系中。我不明白为什么会这样。
此外,我似乎只能将项目添加到关系中 - 能够删除它们也很棒。我可能会问另一个问题。