Django -在一个Django端点中创建多个不同的对象



是否有一种方法来创建一个端点,创建多个对象?我一直在做的是接受请求数据并一次创建一个对象,如果一个失败,然后删除以前创建的实体,这似乎真的真的很糟糕,必须有一个更好的方法来创建多个对象。所以基本上所有的Post都需要与Goal相关联,所以当一个请求来的时候,它将伴随着request.data中与职位相关的数据和与目标相关的数据。因此,它应该首先创建Goal,然后创建与之关联的Post。有没有一种方法可以一气呵成?我的假设是创建一个自定义序列化器来处理这个问题,但不确定如何有效地处理如果Post创建失败,我应该删除Goal的情况。

model.py

class Goal(AbstractBaseModel):
creator_uuid = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_uuid")
goal_category = models.ForeignKey(GoalCategory, on_delete=models.CASCADE)
description = models.CharField(max_length=150, validators=[MinLengthValidator(5)])
class Post(AbstractBaseModel):
creator_uuid = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator_uuid")
goal_uuid = models.ForeignKey(Goal, on_delete=models.CASCADE)
body = post_body

view.py

def post(request):
"""
POST endpoint for current user creating a goal update post
"""
goal_serializer = GoalSerializer(data=request.data)
if goal_serializer.is_valid():
goal_obj = goal_serializer.save()
else:
# return 400 Response

request.data['goal_uuid'] = str(goal_obj.uud)
post_serializer = PostSerializer(data=request.data)

if post_serializer.is_valid():
post_serializer.save()
else:
goal_obj.delete()
# return 400 Response
# return 200 Response

您可以使用try...except将这些序列化器包装在原子块中,如下所示:

from rest_framework.exceptions import ValidationError

def post(request):
try:
with transaction.atomic():
goal_serializer = GoalSerializer(data=request.data)
goal_serializer.is_valid(raise_exception=True)
goal_obj = goal_serializer.save()
request.data['goal_uuid'] = str(goal_obj.uud)
post_serializer = PostSerializer(data=request.data)
post_serializer.is_valid(raise_exception=True)
post_serializer.save()
except ValidationError as e:
# return 400 Response with e as details
# return 200 Response

当序列化器验证失败(或者引发任何异常)时,它将自动回滚atomic块中的所有内容。然后,您可以捕获ValidationError并构建所需的响应。

相关内容

  • 没有找到相关文章

最新更新