Peewee bulk_create返回ID

时间:2019-09-09 09:13:39

标签: python database orm peewee

如果来自bulk_create的peewee中的记录,我需要返回ids

我可以做类似的事情

Sub test()
Application.ScreenUpdating = False
Dim i As Long
Dim ZZ As Long
Dim wkS As Worksheet 'Source
Dim wkD As Worksheet 'Destiny

Set wkD = ThisWorkbook.Worksheets("Sheet1")
Set wkS = ThisWorkbook.Worksheets("Sheet2")

Dim RNumbers As Range 'Range of numbers
Dim RGeoCodes As Range 'Range of GeoCodes
Dim RTypes As Range 'Range of Freight_Types
Dim RFreights As Range 'Range of Freight_Costs

Dim LastRow As Long 'lastrow of data in Sheet2

LastRow = wkS.Range("A" & wkS.Rows.Count).End(xlUp).Row

Set RNumbers = wkS.Range("A2:A" & LastRow)
Set RGeoCodes = wkS.Range("B2:B" & LastRow)
Set RTypes = wkS.Range("C2:C" & LastRow)
Set RFreights = wkS.Range("D2:D" & LastRow)

Dim TextCriteria As String
Dim ThisZone As String

For ZZ = 2 To 7 Step 1 'in my example, data starts at column 2

    i = 4 'in my example, data starts at row 4

    'we get if it's AIR or OCEAN
    Select Case wkD.Cells(i, ZZ).Column
        Case 2 To 4 'columns B,C,D
            TextCriteria = "Air"
        Case 5 To 7 'Columns E,F,G
            TextCriteria = "Ocean"
    End Select

    'We get the zone to sumup
    Select Case UCase(wkD.Cells(3, ZZ).Value) 'in my example, zones are always in row 3
        Case "AP"
            ThisZone = "IN"
        Case "EMEA"
            ThisZone = "DE"
        Case "NA"
            ThisZone = "US"
    End Select

    'We loop with a sumup
    Do Until wkD.Range("A" & i) = ""
        wkD.Cells(i, ZZ).Value = Application.WorksheetFunction.SumIfs(RFreights, RNumbers, wkD.Range("A" & i).Value, RGeoCodes, ThisZone, RTypes, TextCriteria)
        i = i + 1
    Loop
Next ZZ

Application.ScreenUpdating = True

End Sub

我得到一条新记录的ID

但是如果我尝试

from models import Table

t = Table.create(**data)
print(i.id)

在这里我得到一个错误:'t'是'NoneType'

那么我如何从peewee bulk_create获取ID?

1 个答案:

答案 0 :(得分:2)

如果您使用的数据库支持RETURNING,则

Peewee 执行返回ID列表 。因此,如果您使用的是Postgresql,则peewee将返回ID列表。

使用bulk_create()的原因是因为它发出了有效的查询-一次插入许多行。 Sqlite和mysql仅提供“最后插入ID”。