我制作了用于创建更新大小写的API,但是问题出在task
上,如果我在通过邮递员进行更新或创建时仅传递了一个pk like(task = 1),那么它将正常工作,并且将通过引用来创建大小写任务,但任务是一个多领域的领域,我需要将多个任务pk分配给类似task = [1,2]
的情况,然后它给出了
"Incorrect type. Expected pk value, received str."
]
class Case(models.Model):
name = models.CharField(max_length=200)
task = models.ManyToManyField('task.Task',blank=True, null=True)
assigned_to = models.ForeignKey("account.User",null=True, blank=True, on_delete=models.SET_NULL)
class CaseSerializer(serializers.ModelSerializer):
class Meta:
model = Case
fields = ('id', 'name', 'task', 'assigned_to')
class CaseCreateView(APIView):
permission_classes = (IsAuthenticated,)
@access_permission('case_create')
def post(self, request, format=None):
serializer = CaseSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CaseUpdateView(APIView):
permission_classes = (IsAuthenticated,)
model = Case
@access_permission('case_edit')
def put(self, request,pk, format=None):
case = get_object(self,pk)
serializer = CaseSerializer(case,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
我也是DRF的新手,大多数时候我只是使用Generic
,但我会尽力帮助您。在您的序列化器中添加read_only_fields=(task, )
,然后我们将手动向task
实例添加Case
。通过这种方式,在create方法中,我们不需要执行“任务”,序列化器将有效。
serializer.py:
class CaseSerializer(serializers.ModelSerializer):
class Meta:
model = Case
fields = ('id', 'name', 'task', 'assigned_to')
read_only_fields = ('task', )
class CaseUpdateView(APIView):
permission_classes = (IsAuthenticated,)
model = Case
@access_permission('case_edit')
def put(self, request,pk, format=None):
case = get_object(self,pk)
serializer = CaseSerializer(case,data=request.data)
if serializer.is_valid():
serializer.save()
task_id_list = request.data['tasks_id'] # depending on request
for task_id in task_id_list: # this way we can add to M2M field manually
task = Task.object.get(id=task_id)
case.task.add(task)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)