Search code examples
djangotastypie

django-tastypie: Posting to a Resource having ManytoMany field with through relationship


I'm working on a API for a project and I have a relationship Order/Products through OrderProducts like this:

In 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)
    ...

Now, when I load an Order through the API I'd like to get the related Products as well, so I tried this (with django-tastypie):

In order/api.py

class OrderResource(ModelResource):
    products = fields.ToManyField('order.api.ProductResource', products, full=True)

    class Meta:
        queryset = Order.objects.all()
        resource_name = 'order'

Everything works for listing Order resources. I get order resources with product data embedded.

The problem is that I am not able to create or edit Order objects using the api. Since I am using a through model in ManytoMany relation, the ManyToManyField(products) does not have the .add() methods. But tastypie is trying to call .add() on the products field in OrderResource when posting/putting data to it.

{"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"}

Solution

  • The solution lies in overriding the save_m2m() method on the resource. In my case I needed the manytomany field for only listing, so overridden the save_m2m() method to do nothing.