Tastypie,如何在多对多关系中添加元素

8

我正在构建一个Django Tastypie API,并且在添加ManyToMany关系中遇到了问题。

例如,models.py文件如下:

class Picture(models.db):
    """ A picture of people"""
    people = models.ManyToManyField(Person, related_name='pictures',
        help_text="The people in this picture",
    )

class Person(models.db):
    """ A model to represet a person """
    name = models.CharField(max_length=200,
        help_text="The name of this person",
    )

资源:

class PictureResource(ModelResource):
    """ API Resource for the Picture model """
    people = fields.ToManyField(PersonResource, 'people', null=True,
        related_name="pictures", help_text="The people in this picture",
    )
class PersonResource(ModelResource):
    """ API Resource for the Person model """
    pictures = fields.ToManyField(PictureResource, 'pictures', null=True,
        related_name="people", help_text="The pictures were this person appears",
    )

我的问题是我希望在图片资源中添加一个"add_person"终点。如果使用PUT,那么需要指定图片中的所有数据;如果使用PATCH,仍然需要指定图片中的所有人。当然,我可以简单地生成“/api/picture/:id/add_people”URL,在那里处理我的问题。但问题在于这不够干净利落。
另一个解决方案是生成“/api/picture/:id/people”终点,在那里可以像创建新的资源一样进行GET、POST和PUT操作,但我不知道如何实现这个方案,而且在这个资源下创建新的人似乎有些奇怪。
你有什么想法吗?

我以某种方式提出了同样的问题https://dev59.com/4F7Va4cB1Zd3GeqPLJV5 - seb
1
抱歉 @seb,我搜索了我的问题,但没有找到你的问题。如果你愿意,我可以删除我的问题,但请更改你的问题名称,因为“如何通过tasytpie API将产品放入购物车?”太具体了。 - ignacio.munizaga
@seb - 你的问题仍然没有解决,我没有看到你接受了答案! - Mutant
1个回答

4
我通过重写API资源的save_m2m函数来实现这一点。以下是使用您的模型的示例。
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接