私はプロジェクトの API に取り組んでおり、次のように OrderProducts を介して Order/Products の関係があります。
models.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'
Order リソースをリストするためにすべてが機能します。製品データが埋め込まれた注文リソースを取得します。
問題は、API を使用して Order オブジェクトを作成または編集できないことです。ManytoMany 関係でスルー モデルを使用しているため、ManyToManyField(products) には .add() メソッドがありません。しかし、tastypie は、データを投稿/配置するときに OrderResource の products フィールドで .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"}