Tastypie, add element to a many to many relationship

故事扮演 提交于 2019-11-29 10:05:29

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