我有2种型号:打印机和支票
class Printer(models.Model):
name = models.CharField(...)
api_key = models.CharField(...)
check_type = models.CharField(...)
point_id = models.IntegerField()
class Check(models.Model):
printer_id = models.ForeignKey(Printer, on_delete=models.CASCADE)
type = models.CharField(...)
order = JSONField(...)
status = models.CharField(...)
pdf_file = models.FileField(...)
我正在使用Django REST Framework构建API。我收到的POST请求应该看起来像这样:
{
"id": 123456,
"price": 780,
"items": [
{
"name": "pizza",
"quantity": 2,
"unit_price": 250
},
{
"name": "rolls",
"quantity": 1,
"unit_price": 280
}
],
"address": "some address",
"client": {
"name": "John",
"phone": his phone
},
"point_id": 1
}
每个点(做饭的地方)都有两台打印机。我需要创建两个 Check 对象,以便为厨房创建一个“检查”打印,为客户创建一个。为此,我将使用请求中的“ point_id”并创建两个Check
@api_view(['POST'])
def create_checks(request):
queryset = Check.objects.all()
orderid = #order_id from request
point = #point_id from request
jsonorder = #request body converted to json
printers = Printer.objects.filter(point_id=point)
kitchencheck = Check(printer_id=Printer.objects.get(name=printers[0].name),
type="kitchen", order=jsonorder,status="new")
clientcheck = Check(printer_id=Printer.objects.get(name=printers[1].name),
type="client", order=jsonorder,status="new")
kitchencheck.save()
clientcheck.save()
return Response({"Success": "Checks created successfully"}, status=status.HTTP_200_OK)
1。如何从请求中获取order_id和point_id?
2.如何将请求正文转换为JSON文件?
3.有更简单的方法吗?我花了整整一天的时间来了解DRF,“结果”看起来过于庞大且不现实
答案 0 :(得分:1)
这是串行器的作用。 (https://www.django-rest-framework.org/api-guide/serializers/)在视图级别,通过序列化器传递您的请求,这将为您提供validated_data
负载。这又可以用来创建模型实例。如果您需要从一组数据中创建两个模型,只需重复最后一步两次即可。
class CheckSerializer(serializers.Serializer):
id = serializers.CharField()
point_id = serializers.CharField()
# etc ..
@api_view(['POST'])
def create_checks(request):
queryset = Check.objects.all()
serializer = CheckSerializer(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
printers = Printer.objects.filter(point_id=serializer.validated_data['point_id'])
kitchencheck = Check(
printer_id=Printer.objects.get(name=printers[0].name),
type="kitchen",
order=jsonorder,
status="new"
)
clientcheck = Check(
printer_id=Printer.objects.get(name=printers[1].name),
type="client",
order=jsonorder,
status="new"
)
kitchencheck.save()
clientcheck.save()
return Response({"Success": "Checks created successfully"}, status=status.HTTP_200_OK)