我有一个简单的“ Driver” Django模型,其中包含“ id”,“ phone”和“ address”字段。我添加了一个序列化程序和一个请求处理程序,以从数据库中返回最后一个驱动程序,如下所示。 当我传递单个实例驱动程序对象时,序列化程序将返回空数据。但是,如果我通过与列表相同的对象并设置many = True,则它将最后一个驱动程序作为列表返回。任何想法如何使序列化程序与实例参数一起工作,而不是将其包装在列表中?
def get_last_driver(request):
last_driver_object = Driver.objects.last()
# This returns empty data {"last_driver": null}
last_driver_data = DriverSerializer(last_driver_object).data
# This results a list containing one object : {"last_driver": [{"id": 3, "phone": "0123456", "address": "DemoSteet 12"}]}
last_driver_data = DriverSerializer([last_driver_object], many=True).data
return JsonResponse({"last_driver": last_driver_data})
class DriverSerializer(serializers.ModelSerializer):
class Meta:
model = Driver
fields = ("id", "phone", "address")
class Driver(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='driver')
avatar = models.CharField(max_length=500)
phone = models.CharField(max_length=500, blank=True)
address = models.CharField(max_length=500, blank=True)
def __str__(self):
return self.user.get_full_name()
答案 0 :(得分:1)
我认为您的数据库不包含任何数据。因此,在使用API时添加一些响应,例如
from rest_framework.response import Response
def get_last_driver(request):
if not SampleModel.objects.exists(): # if atleast one object is there
return Response(data={"message": "There is no 'Driver' object in DB"})
last_driver_object = Driver.objects.last()
serializer = DriverSerializer(last_driver_object)
return Response(data=serializer.data)
,在您的序列化程序中,不需要 return
语句,因为return
中使用了functions
。因此,您的序列化器将是
class DriverSerializer(serializers.ModelSerializer):
class Meta:
model = Driver
fields = ("id", "phone", "address")