在Django PUT请求中,当我每周更新位置和小时数时,PUT请求返回的值完全相同,并且未更新任何内容。
下面是我的代码,
URL
url(
r'^api/availability', views.AvailabilityAPIView.as_view(),name='api_availability'
)
模型
class Availability(models.Model):
# Skill model which contains trainer's skill details
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
locations = models.CharField(max_length=2000)
hours_per_week = models.IntegerField(default=0)
def __str__(self):
return self.locations + "|" + str(self.hours_per_week)
序列化器
class AvailabilitySerializer(serializers.ModelSerializer):
class Meta:
model = Availability
fields = ['user', 'locations', 'hours_per_week']
观看次数
class AvailabilityAPIView(APIView):
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
def get(self, request):
availability = Availability.objects.all()
serializer = AvailabilitySerializer(availability, many=True)
return Response(serializer.data)
def put(self, request):
serializer = AvailabilitySerializer(request.user, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
请帮助了解我在做什么错。我需要通过url传递PK并更新特定的PK吗?
答案 0 :(得分:1)
您需要传递Availability
模型的实例。
def put(self, request):
instance = Availability.objects.get(user=request.user)
serializer = AvailabilitySerializer(instance, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)