我正在构建一个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操作,但我不知道如何实现这个方案,而且在这个资源下创建新的人似乎有些奇怪。
你有什么想法吗?