英文:
How to save list of objects in DRF
问题
我是Django的新手。我有以下模型:
class Standup(models.Model):
team = models.ForeignKey("Team", on_delete=models.CASCADE)
standup_time = models.DateTimeField(auto_now_add=True)
employee = models.ForeignKey("Employee", on_delete=models.CASCADE)
update_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=50)
work_done_yesterday = models.TextField()
work_to_do = models.TextField()
blockers = models.TextField()
序列化器类如下:
class StandupSerializer(serializers.ModelSerializer):
class Meta:
model = Standup
fields = '__all__'
Viewset如下:
class StandupDetail(viewsets.ModelViewSet):
queryset = Standup.objects.all()
serializer_class = StandupSerializer
我的任务是访问一个单一的API,该API将保存所有员工的数据,而不是分别保存员工的数据。在当前的实现中,每个员工都必须分别访问API以将数据保存到数据库中。每个员工都会首先选择团队,因为一个员工可以是多个团队的一部分。我们将保存一个对象列表。有关如何执行此操作的任何建议吗?
英文:
I am new to django. I have following model:
class Standup(models.MOdel):
team = models.ForeignKey("Team", on_delete=models.CASCADE)
standup_time = models.DateTimeField(auto_now_add=True)
employee = models.ForeignKey("Employee", on_delete=models.CASCADE)
update_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=50)
work_done_yesterday = models.TextField()
work_to_do = models.TextField()
blockers = models.TextField()
Serializer class looks like this:
class StandupSerializer(serializers.ModelSerializer):
class Meta:
model = Standup
fields = '__all__'
Viewset is like this:
class StandupDetail(viewsets.ModelViewSet):
queryset = Standup.objects.all()
serializer_class = StandupSerializer
My task is to hit a single API which will save the data of all employees, instead of saving the data of employees separately. In the current implementation, each employee will have to hit the API separately to save the data in database. Each employee will select team first, as one employee can be a part of multiple team. We will save a list of objects. Any leads on how to do it?
答案1
得分: 2
尝试将数据列表传递到请求主体中。您需要修改您的序列化器,以及覆盖用于批量创建和保存数据的create方法。您可以按照这个链接操作。
https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create
英文:
Try to pass a list of data in request body. You need to modify your serializer as well as override the create for bulk creation and saving of data. You can follow this.
https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-create
答案2
得分: 1
Django提供了bulk_create
方法来实现这个功能。
例如,您可以将以下函数放入视图集中的适当类中:
def bulk_update_standup(self, request, *args, **kwargs):
standup_list = request.data.get("standupList", [])
qs = []
for item in standup_list:
serializer = StandupSerializer(data=item)
standup_instance = Standup(**serializer.validated_data)
qs.append(standup_instance)
Standup.objects.bulk_create(qs)
data = {"data": None, "message": "Saved Successfully"}
return Response(data=data, status=status.HTTP_200_OK)
英文:
Django provides bulk_create method for achieving that.
For example you can put the below function in your appropriate class in viewset:
def bulk_update_standup(self, request, *args, **kwargs):
standup_list = request.data.get("standupList", [])
qs = []
for item in standup_list:
serializer = StandupSerializer(data=item)
standup_instance = Standup(**serializer.validated_data)
qs.append(standup_instance)
Standup.objects.bulk_create(qs)
data = {"data": None, "message": "Saved Successfully"}
return Response(data=data, status=status.HTTP_200_OK)
答案3
得分: 0
你可以重写create方法。
def create(self, request, *args, **kwargs):
if isinstance(request.data, list):
serializer = self.get_serializer(data=request.data, many=True)
else:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
英文:
You can override create method.
def create(self, request, *args, **kwargs):
if isinstance(request.data, list):
serializer = self.get_serializer(data=request.data, many=True)
else:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论