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

后端 未结 3 1501
既然无缘
既然无缘 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: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.

提交回复
热议问题