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

后端 未结 3 1503
既然无缘
既然无缘 2021-01-05 20:10

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         


        
相关标签:
3条回答
  • 2021-01-05 20:38

    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.

    0 讨论(0)
  • 2021-01-05 20:51

    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.

    0 讨论(0)
  • 2021-01-05 20:56

    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'
    
    0 讨论(0)
提交回复
热议问题