如何通过序列化程序 post 数组数据?
How to post array data through serializers?
我想 post 通过序列化程序的创建方法来获取一些数组数据。如何在serializer的create方法中获取数组数据?
这是我的结果,由于数组的数据而出错。我必须 post 下面特别说明,inch_first...对数组数据进行评分。
{
"order_media": {
"client_employee": "4",
"client": "63",
"narration": "Print ad",
"vendor": "68",
"total_amount": "2590.00",
"discount_rate_client": "10.00",
"discount_amount_client": "259.00",
"service_percentage": "10.00",
"service_amount": "259.00",
"client_vat": "388.50",
"total_receivable": "2978.50",
},
"pub_date": "2019-04-03",
"particular": ["Banner", "Poster", "Plastic banner"],
"inch_first": ["4", "5", "3"],
"inch_second": ["4", "5", "3"],
"size": ["16.00", "25.00", "9.00"],
"quantity": ["5", "5", "6"],
"rate": ["10", "10", "10"],
}
这是我的模型
class RequestPrintProduction(models.Model):
particular = models.CharField(max_length=255,null=True,blank=True)
inch_first = models.CharField(max_length=45,null=True,blank=True)
inch_second = models.CharField(max_length=45,null=True,blank=True)
size = models.CharField(max_length=45,blank=True, null=True)
quantity = models.CharField(max_length=45,null=True, blank=True)
rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal(0.00), null=True, blank=True)
pub_date = models.DateField(blank=True, null=True)
vendor = models.ForeignKey(Party, blank=True, null=True)
request_id = models.ForeignKey(Request, blank=True, null=True, related_name='requestprint')
def __str__(self):
return self.particular
这是我的 api 观点:
class PrintRequestAPIView(ListBulkCreateAPIView):
serializer_class = RequestPrintSerializer
这是我的序列化程序:
class RequestPrintSerializer(serializers.ModelSerializer):
order_media = OrderMediaSerializer(required=False)
class Meta:
model = RequestPrintProduction
fields = '__all__'
def create(self, validated_data):
service_request = Request()
service_request.save()
validated_data['request_id'] = service_request
order_media = validated_data.pop('order_media')
print(order_media)
online_service_request = self.Meta.model.objects.create(**data)
order_media['request_id'] = service_request
order_media = OrderMedia.objects.create(**order_media)
return online_service_request
我希望post数组的数据成功。
您的数据库中似乎有一个 char 字段,但想 post 一个数组到 DRF。实际上,正如评论中提到的,这几乎是您所有领域的问题。你似乎通过在任何地方传递字符串来解决这个问题。
没有数据库支持,这将无法直接运行。但是,如果您 do 真的想这样做,那么您将不得不在自己的代码中完成一些工作。在某处可能有 个自定义字段,但我从未见过它们。
JSON Post 仅
这里有一个简单的方法来做到这一点:
- 直接将序列化器上的字段声明为 ListField
- 在'validate'函数中,转换为字符串(csv、json.dumps等)
- 请注意,我没有检查空值、设置默认值等。请自行阅读 ListField 的文档(和源代码)。
class Serializer(ModelSerializer):
particular = ListField(child=CharField(max_length=10))
def validate_particular(self, value):
"""Convert the list to a json string, and do extra validation if needed"""
return json.dumps(value)
输入和输出(Post 和获取)
如果您将其用于输入和输出,并希望从您的模型中 return 一个列表,您将需要创建一个自定义字段:
class ListAsJsonField(fields.ListField):
"""
Converts an incoming list of string values to json.
This field is _very_ primitive, lots of edge cases may break it.
"""
child = fields.CharField(min_length=1) # always use a char field
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_representation(self, data):
"""Convert to our output representation. Assumes input is always valid json now"""
return json.loads(data)
def to_internal_value(self, data):
"""Convert to the internal value -> database (and validated_data)"""
return json.dumps(data)
class MySerializer(serializers.ModelSerializer):
particular = ListAsJsonField(required=True, min_length=1)
...
备注:
像 postgres 这样的一些数据库有一个自定义的 JSON 字段和数组字段。 Django 附带 django.contrib.postgres
中的字段。使用这些意味着您还想修复其他模型问题。
ListBulkCreateAPIView
到底是什么?
让我们尝试按如下方式排列 post 数据。然后每当您为此请求初始化 RequestPrintSerializer
时,使用 many=True 初始化序列化程序。希望能帮助到你。祝你好运。
{
"order_media": {
"client_employee": "4",
"client": "63",
"narration": "Print ad",
"vendor": "68",
"total_amount": "2590.00",
"discount_rate_client": "10.00",
"discount_amount_client": "259.00",
"service_percentage": "10.00",
"service_amount": "259.00",
"client_vat": "388.50",
"total_receivable": "2978.50"
},
"request_print_production": [
{
"pub_date" : "2019-04-03",
"particular": "Banner",
"inch_first": "4",
"inch_second": "4",
"size": "16.00",
"quantity": "5",
"rate": "10"
},
{
"pub_date" : "2019-04-03",
"particular": "Poster",
"inch_first": "5",
"inch_second": "5",
"size": "25.00",
"quantity": "5",
"rate": "10"
},
{
"pub_date" : "2019-04-03",
"particular": "Plastic Banner",
"inch_first": "3",
"inch_second": "3",
"size": "9.00",
"quantity": "6",
"rate": "10"
}
]
}
我想 post 通过序列化程序的创建方法来获取一些数组数据。如何在serializer的create方法中获取数组数据?
这是我的结果,由于数组的数据而出错。我必须 post 下面特别说明,inch_first...对数组数据进行评分。
{
"order_media": {
"client_employee": "4",
"client": "63",
"narration": "Print ad",
"vendor": "68",
"total_amount": "2590.00",
"discount_rate_client": "10.00",
"discount_amount_client": "259.00",
"service_percentage": "10.00",
"service_amount": "259.00",
"client_vat": "388.50",
"total_receivable": "2978.50",
},
"pub_date": "2019-04-03",
"particular": ["Banner", "Poster", "Plastic banner"],
"inch_first": ["4", "5", "3"],
"inch_second": ["4", "5", "3"],
"size": ["16.00", "25.00", "9.00"],
"quantity": ["5", "5", "6"],
"rate": ["10", "10", "10"],
}
这是我的模型
class RequestPrintProduction(models.Model):
particular = models.CharField(max_length=255,null=True,blank=True)
inch_first = models.CharField(max_length=45,null=True,blank=True)
inch_second = models.CharField(max_length=45,null=True,blank=True)
size = models.CharField(max_length=45,blank=True, null=True)
quantity = models.CharField(max_length=45,null=True, blank=True)
rate = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal(0.00), null=True, blank=True)
pub_date = models.DateField(blank=True, null=True)
vendor = models.ForeignKey(Party, blank=True, null=True)
request_id = models.ForeignKey(Request, blank=True, null=True, related_name='requestprint')
def __str__(self):
return self.particular
这是我的 api 观点:
class PrintRequestAPIView(ListBulkCreateAPIView):
serializer_class = RequestPrintSerializer
这是我的序列化程序:
class RequestPrintSerializer(serializers.ModelSerializer):
order_media = OrderMediaSerializer(required=False)
class Meta:
model = RequestPrintProduction
fields = '__all__'
def create(self, validated_data):
service_request = Request()
service_request.save()
validated_data['request_id'] = service_request
order_media = validated_data.pop('order_media')
print(order_media)
online_service_request = self.Meta.model.objects.create(**data)
order_media['request_id'] = service_request
order_media = OrderMedia.objects.create(**order_media)
return online_service_request
我希望post数组的数据成功。
您的数据库中似乎有一个 char 字段,但想 post 一个数组到 DRF。实际上,正如评论中提到的,这几乎是您所有领域的问题。你似乎通过在任何地方传递字符串来解决这个问题。
没有数据库支持,这将无法直接运行。但是,如果您 do 真的想这样做,那么您将不得不在自己的代码中完成一些工作。在某处可能有 个自定义字段,但我从未见过它们。
JSON Post 仅
这里有一个简单的方法来做到这一点:
- 直接将序列化器上的字段声明为 ListField
- 在'validate'函数中,转换为字符串(csv、json.dumps等)
- 请注意,我没有检查空值、设置默认值等。请自行阅读 ListField 的文档(和源代码)。
class Serializer(ModelSerializer):
particular = ListField(child=CharField(max_length=10))
def validate_particular(self, value):
"""Convert the list to a json string, and do extra validation if needed"""
return json.dumps(value)
输入和输出(Post 和获取)
如果您将其用于输入和输出,并希望从您的模型中 return 一个列表,您将需要创建一个自定义字段:
class ListAsJsonField(fields.ListField):
"""
Converts an incoming list of string values to json.
This field is _very_ primitive, lots of edge cases may break it.
"""
child = fields.CharField(min_length=1) # always use a char field
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_representation(self, data):
"""Convert to our output representation. Assumes input is always valid json now"""
return json.loads(data)
def to_internal_value(self, data):
"""Convert to the internal value -> database (and validated_data)"""
return json.dumps(data)
class MySerializer(serializers.ModelSerializer):
particular = ListAsJsonField(required=True, min_length=1)
...
备注:
像 postgres 这样的一些数据库有一个自定义的 JSON 字段和数组字段。 Django 附带 django.contrib.postgres
中的字段。使用这些意味着您还想修复其他模型问题。
ListBulkCreateAPIView
到底是什么?
让我们尝试按如下方式排列 post 数据。然后每当您为此请求初始化 RequestPrintSerializer
时,使用 many=True 初始化序列化程序。希望能帮助到你。祝你好运。
{
"order_media": {
"client_employee": "4",
"client": "63",
"narration": "Print ad",
"vendor": "68",
"total_amount": "2590.00",
"discount_rate_client": "10.00",
"discount_amount_client": "259.00",
"service_percentage": "10.00",
"service_amount": "259.00",
"client_vat": "388.50",
"total_receivable": "2978.50"
},
"request_print_production": [
{
"pub_date" : "2019-04-03",
"particular": "Banner",
"inch_first": "4",
"inch_second": "4",
"size": "16.00",
"quantity": "5",
"rate": "10"
},
{
"pub_date" : "2019-04-03",
"particular": "Poster",
"inch_first": "5",
"inch_second": "5",
"size": "25.00",
"quantity": "5",
"rate": "10"
},
{
"pub_date" : "2019-04-03",
"particular": "Plastic Banner",
"inch_first": "3",
"inch_second": "3",
"size": "9.00",
"quantity": "6",
"rate": "10"
}
]
}