Django:为save.method

时间:2018-06-20 14:29:14

标签: django

当前,我正以这种方式将数据添加到我的模型表单中:new_order =

order.save(commit=False)
new_order.total_gross = total_amount
new_order.total_tax = total_tax_amount
new_order.total_gross_converted = total_amount  # TODO Marc
new_order.event = event
new_order.order_reference = session_order_reference
new_order.status = 'pending' # TODO Marc
new_order.save()

我现在想知道是否有一种“更好” /更干净的方法。有人做过吗?

不幸的是,这是行不通的:

new_order_dict = {
    'total_gross': total_amount,
    'total_tax': total_tax_amount,
    'total_gross_converted': total_amount,
    'event': event,
    'order_reference': session_order_reference,
    'status': 'pending',
}

new_order = order.save(commit=False)
new_order.append(**new_order_dict)
new_order.save()

1 个答案:

答案 0 :(得分:3)

一种简单的解决方法是使用UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [insert] on [test.products] at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:598:61 at authenticateStragglers (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:516:16) at Connection.messageHandler (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:552:5) at emitMessageHandler (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\connection.js:309:10) at TLSSocket.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\connection.js:452:17) at TLSSocket.emit (events.js:180:13) at addChunk (_stream_readable.js:274:12) at readableAddChunk (_stream_readable.js:261:11) at TLSSocket.Readable.push (_stream_readable.js:218:10) at TLSWrap.onread (net.js:581:20) (node:21692) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

setattr(..)

这是有效的,因为for k, v in new_order_dict.items(): setattr(new_order, k, v) new_order.save() 等效于setattr(x, 'y', z)(请注意,在x.y = z中,我们在字符串中使用setattr(..))。因此,我们遍历字典的'y'(一个2元组的迭代,其中每个元组都包含一个 key .items() value {{1 }}),然后调用k将名称为v的属性设置为setattr(..)

最后,我们执行k