我有一个包含3个字段的模型示例。
class Example(models.Model):
name = models.CharField(max_length=200, null=False, blank=False)
number = models.CharField(max_length=200, null=False, blank=False)
address = models.CharField(max_length=200)`
我有一个Post API(其余框架)。这将有多个对象。我想解析这个数组并将每个对象存储在我的数据库中。这是Views.py
class PostExample(APIView):
def post(self, request, format=None):
example_records = request.POST["example_data"]
print example_records
这里“example_data”是键,值将是一个数组。示例值:
[
{
"name": "test",
"address": "address",
"number": 123456789
},
{
...
}
]
我无法遍历“example_records”。 “example_records”打印数组但无法从中获取每个对象。如何实现这个??
答案 0 :(得分:1)
您可以在此处使用Sub Compare()
'Set primary Workbook
'Find last cell
Dim WS As Worksheet
Dim LastCellRowNumber As Long
Set WS = ThisWorkbook.Sheets("Sheet1")
LastCellRowNumber = WS.Cells(WS.Rows.Count, "A").End(xlUp).Row
'MsgBox (LastCell.Row)
'Adding Index Column
WS.Columns("A:A").Insert Shift:=xlToRight
WS.Range("A2:A" & LastCellRowNumber).Formula = "=G2&H2"
'adding headers
WS.Range("AG1").Value = "Resale"
WS.Range("AH1").Value = "Cost"
WS.Range("AI1").Value = "disti"
'open company quotes
Dim wbCompQuotes As Workbook
Set wbCompQuotes = Workbooks.Open ("R:\company\DATA\company quotes.xlsx")
'find last cell'
Dim wsQuoteSum As Worksheet
Dim LastCellRowNumberq As Long
Set wsQuoteSum = wbCompQuotes.Worksheets("Quote Summary")
LastCellRowNumberq = wsQuoteSum.Cells(wsQuoteSum.Rows.Count, "A").End(xlUp).Row
'MsgBox (LastCell.Row)
wsQuoteSum.Columns("A:A").Insert Shift:=xlToRight
wsQuoteSum.Range("A2:A" & LastCellRowNumberq).Formula = "=J2&B2"
Dim i As Long
For i = 2 To LastCellRowNumber
WS.Range("AG" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 17, False)
WS.Range("AH" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 19, False)
WS.Range("AI" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 20, False)
Next i
End Sub
模块。首先将json
字符串数据转换为example_records
对象,然后解析json
,最后遍历所有。
Example value
然后您可以通过传递相应的import json
data = '''{"Example value":[{"name":"test1","address":"address1","number":123456789},{"name":"test2","address":"address2","number":123456789}]}'''
jobject = json.loads(data)
for val in jobject['Example value']:
print(val)
{'address': 'address1', 'name': 'test1', 'number': 123456789}
{'address': 'address2', 'name': 'test2', 'number': 123456789}
来简单地提取values
,例如:
key
答案 1 :(得分:0)
request.POST
是POST期间收到的原始数据,它是一个json字符串。
您可以按照某些用户的建议使用json
模块,但Django Rest Framework可以为您完成工作:{{3}}。这就是使用像DRF这样的框架的重点。
class PostExample(APIView):
def post(self, request, format=None):
example_records = request.data["example_data"]
for record in example_records:
...