我正在为一个项目开发一个 API,并且我通过 OrderProducts 与 Order/Products 建立了关系,如下所示:
在模型.py
class Product(models.Model):
...
class Order(models.Model):
products = models.ManyToManyField(Product, verbose_name='Products', through='OrderProducts')
...
class OrderProducts(models.Model):
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
...
现在,当我通过 API 加载订单时,我也想获得相关的产品,所以我尝试了这个(使用 django-tastypie):
按顺序/api.py
class OrderResource(ModelResource):
products = fields.ToManyField('order.api.ProductResource', products, full=True)
class Meta:
queryset = Order.objects.all()
resource_name = 'order'
一切都适用于列出订单资源。我得到嵌入了产品数据的订单资源。
问题是我无法使用 api 创建或编辑 Order 对象。由于我在多对多关系中使用直通模型,因此 ManyToManyField(products) 没有 .add() 方法。但是,当向 OrderResource 中的 products 字段发布/放置数据时,tastepie 会尝试调用 .add() 。
{"error_message": "'ManyRelatedManager' object has no attribute 'add'", "traceback": "Traceback (most recent call last):\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/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/tastypie/resources.py\", line 1784, in obj_create\n self.save_m2m(m2m_bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1954, in save_m2m\n related_mngr.add(*related_objs)\n\nAttributeError: 'ManyRelatedManager' object has no attribute 'add'\n"}