代码之家  ›  专栏  ›  技术社区  ›  Zain Khan

在django rest框架中批量创建记录的最佳方法

  •  0
  • Zain Khan  · 技术社区  · 2 年前

    我是Django的新手,目前正在创建我的记录,但我想要一种更有效的方法,可以减少服务器上的时间和负载。请让我知道最好的方法,以创造大量记录与外国人的关系。

    models.py

    class Task(models.Model):
        name = models.CharField(max_length=255, default='')
        description = models.CharField(max_length=255, null=True, blank=True)
        project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True)
        account = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    
        class Meta:
            db_table = 'tasks'
    

    views.py

    @api_view(['POST'])
    def create_task(request): # added request JSON below
        try:
            response = []
            for task in request.data:
                data = {}
                data['name'] = task['name']
                data['description'] = task['description']
                data['project'] = task['project_id']
                data['account'] = task['user_id']
                serializer = TaskSerializer(data=data)
                serializer.is_valid()
                serializer.save()
                response.append(serializer.data)
            return Response(response)
        except Exception as e:
            return Response(str(e))
    

    serializers.py

    class TaskSerializer(serializers.ModelSerializer):
        project = ProjectSerializer(read_only=True) # added to fetch project detail in get request
        user = UserSerializer(read_only=True) # added to fetch user detail in get request
        class Meta:
            model = Task
            fields = ['id', 'name', 'description', 'project', 'user']
    

    request from client side

    [
      {
        "name": "foo",
        "description": "lorem ipsum",
        "project_id": 1,
        "user_id": 1
      },
      {
        "name": "bar",
        "description": "lorem ipsum",
        "project_id": 1,
        "user_id": 2
      },
      {
        "name": "baz",
        "description": "lorem ipsum",
        "project_id": 1,
        "user_id": 3
      }
    ]
    
    0 回复  |  直到 2 年前