gpt4 book ai didi

django - Tastypie,为多对多关系添加元素

转载 作者:行者123 更新时间:2023-12-04 08:36:54 26 4
gpt4 key购买 nike

我正在构建一个 django 美味的 api,我在 ManyToMany 中添加元素时遇到问题关系

例子,
模型.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 ,就像它是一个新资源,但我不知道如何实现这一点,在此资源下创建新人似乎很奇怪。

有什么想法吗?

最佳答案

我通过覆盖 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)

关于django - Tastypie,为多对多关系添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10111734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com