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

只谈情不闲聊 提交于 2019-11-30 21:04:45

Since you needed the manytomany field only for listing, a better solution is to add readonly=True on OrderResource's products field. This removes the need of overriding save_m2m method. For completeness:

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

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

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.

If you are allowed to modify class OrderProducts, adding auto_created = True might solve your problem, i.e.,

class OrderProducts(models.Model): 
    class Meta:
        auto_created = True

If you cannot change class OrderProducts, try the following tastypie patch.

---------------------------- tastypie/resources.py ----------------------------
index 2cd869e..aadf874 100644
@@ -2383,7 +2383,20 @@ class BaseModelResource(Resource):
                     related_resource.save(updated_related_bundle)
                 related_objs.append(updated_related_bundle.obj)

-            related_mngr.add(*related_objs)
+            if hasattr(related_mngr, 'through'):
+                through = getattr(related_mngr, 'through')
+                if not through._meta.auto_created:
+                    for related_obj in related_objs:
+                        args = dict()
+                        args[related_mngr.source_field_name] = bundle.obj
+                        args[related_mngr.target_field_name] = related_obj
+                        through_obj = through(**args)
+                        through_obj.save()
+                else:
+                    related_mngr.add(*related_objs)
+            else:
+                related_mngr.add(*related_objs)

     def detail_uri_kwargs(self, bundle_or_obj):
         """

In Django 1.7, the error message is changed to "Cannot set values on a ManyToManyField which specifies an intermediary model". The solution is the same.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!