Tastypie, add element to a many to many relationship

后端 未结 1 659
耶瑟儿~
耶瑟儿~ 2020-12-19 05:04

I\'m building a django tastypie api, and I have a problem with adding elements in ManyToMany relationships

Example, models.py

class Pict         


        
相关标签:
1条回答
  • 2020-12-19 05:48

    I implemented this by overriding the save_m2m function of the API Resource. Here is an example using your models.

    def save_m2m(self, bundle):
        for field_name, field_object in self.fields.items():
            if not getattr(field_object, 'is_m2m', False):
                continue
    
            if not field_object.attribute:
                continue
    
            if field_object.readonly:
                continue
    
            # Get the manager.
            related_mngr = getattr(bundle.obj, field_object.attribute)
                # This is code commented out from the original function
                # that would clear out the existing related "Person" objects
                #if hasattr(related_mngr, 'clear'):
                # Clear it out, just to be safe.
                #related_mngr.clear()
    
            related_objs = []
    
            for related_bundle in bundle.data[field_name]:
                # See if this person already exists in the database
                try:
                    person = Person.objects.get(name=related_bundle.obj.name)
                # If it doesn't exist, then save and use the object TastyPie
                # has already prepared for creation
                except Person.DoesNotExist:
                    person = related_bundle.obj
                    person.save()
    
                related_objs.append(person)
    
            related_mngr.add(*related_objs)
    
    0 讨论(0)
提交回复
热议问题