在放置请求 Django Rest 框架时键入错误



我正在构建一个Django应用程序,其中有一个名为Location的模型和另一个称为Property的模型。每当我尝试给出放置请求时,它都会向我显示类型错误TypeError: Object of type Location is not JSON serializable

我的位置模型

class Location(models.Model):
lat = models.DecimalField(max_digits=10,decimal_places=8)
long = models.DecimalField(max_digits=10,decimal_places=8)
address = models.CharField(max_length=256)
class Property(models.Model):
owner = models.OneToOneField(to=User,on_delete=models.CASCADE)
name = models.CharField(max_length=256)
bedrooms = models.SmallPositiveIntigerField()
bathrooms = models.SmallPositiveIntigerField()
living_rooms = models.SmallPositiveIntigerField()
location = models.ForeignKey(to=Location,null=True,on_delete=models.SETNULL)

序列化程序

class PropertySerializer(serializers.ModelSerializer):
class Meta:
model = Property
fields = ['id','name','bedrooms','bathrooms','living_rooms','location']
read_only_fields = ['id']
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ['id','long','lat','address']
read_only_fields = ['id']

视图

class RenterCreate(APIView):

authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated, RenterPermission]
renderer_classes = [JSONRenderer]

def get(self, request):

property = Property.objects.all()
serializer = RenterSerializer(property , many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

def post(self, request):
serializer = PropertySerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
def put(self, request):
serializer = PropertySerializer(request.user, data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

保存属性后,当我使用 PUT 请求更新它显示的信息时TypeError: Object of type Location is not JSON serializable我在数据库中保存了几个位置。 首先,我用它提出了一个帖子请求,它给了我STATUS 201 CREATED

{
'name': 'foo',
'bedrooms':4,
'bathrooms':3,
'living_rooms':5,
'location':4,
}

然后我对其执行放置请求

{
'name': 'foo bar',
'bedrooms':1,
'bathrooms':2,
'living_rooms':2,
'location':1,
}

它给了我TypeError: Object of type Location is not JSON serializable

你的代码有很多问题。GET 和 POST 请求在列表终结点上正常工作,但 PUT 请求应在详细信息终结点上工作。这意味着端点应该允许您指定要编辑的特定Property对象,但目前尚未指定。除此之外,您不是将要编辑的Property实例传递给序列化程序,而是传递request.user

通常,如果您使用的是低级 APIView,则需要为列表和详细信息端点创建单独的视图。如果要使用一个视图,则应利用组合列表视图和详细信息视图的更高级别视图集。而且它们非常容易实现,因为大多数样板代码已经为您实现。对于您的情况,像这样的简单视图集就足够了。

from rest_framework import viewsets
class PropertyViewSet(viewsets.ModelViewSet):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated, RenterPermission]
renderer_classes = [JSONRenderer]
serilaizer_class = PropertySerializer
queryset = Property.objects.all()

然后在 urls.py 中注册它,如下所示:

from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'properties', PropertyViewSet, basename='properties')
urlpatterns = router.get_urls()

它自动实现了获取、发布、放置和删除,并包含两个终结点:api/properties称为列表终结点,api/properties/<id>/终结点称为详细信息终结点。

因此,要编辑 id 为 2 的属性的属性,您应该将 PUT 请求发送到api/properties/2/

您还可以阅读有关 DRF 视图集的详细信息

PropertySerializer中,您需要在"location"属性中添加PrimaryKeyRelatedFieldLocationSerializer

class PropertySerializer(serializers.ModelSerializer):
location = PrimaryKeyRelatedField()
class Meta:
model = Property
fields = ['id','name','bedrooms','bathrooms','living_rooms','location']
read_only_fields = ['id']

或:

class PropertySerializer(serializers.ModelSerializer):
location = LocationSerializer()
class Meta:
model = Property
fields = ['id','name','bedrooms','bathrooms','living_rooms','location']
read_only_fields = ['id']

我相信在 RenterCreate 视图中也有一种方法可以做到这一点,但请先让我知道其中任何一个是否有效。

在你的 PUT 方法(put(self, request)(,你使用 request.user 作为 PropertySerializer 的对象而不是属性对象。您可以查看序列化程序文档以保存对象。

您可以按照这个精彩的 DRF 教程来设置您的 APIViews 和 urls.py 获取/放置/发布方法。

然后,您可以毫无问题地创建、更新和获取对象。

我发现了问题并解决了这件事 序列化程序和模型是相同的,但我改变了视图。


class PropertyView(viewsets.ModelViewSet):
# Adding Authentication classes Token Authentication
# Permission class > Will allow only post request if user is not authenticated
authentication_classes = [TokenAuthentication]
# Permissions only allow renters and authenticated users
permission_classes = [IsAuthenticated, RenterPermission]
# Gives JSON Rendered Class
renderer_classes = [JSONRenderer]
# Serializer Class for this Class View
serializer_class = PropertySerializer
# Query set of all renter objects
queryset = Renter_Property_Pref.objects.all()

@action(methods=['get'], detail=True)
def retrieve(self, request, pk=None):

renter = get_object_or_404(self.queryset, user=request.user)
serializer = self.get_serializer(renter, many=False)
return Response(serializer.data, status=status.HTTP_200_OK)
@action(methods=['post'], detail=True)
def create(self, request):
# giving serializer the data from request data
serializer = self.get_serializer(data=request.data)
# checks if serializer is valid
if serializer.is_valid():
# saves user information and saves it
serializer.save(user=self.request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
# Otherwise it will return errors and a bad request
return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)

@action(methods=['put'], detail=True)
def update(self, request):
# Propery Serializer and instance object
instance = Property.objects.get(owner=request.user)
serializer = self.get_serializer(instance=instance, data=request.data)
# If serializer is valid it will save
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
# Otherwise it will show error
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)**

最新更新