Django 1.9 - 更新或创建,返回添加/编辑的 id

Ale*_*exW 0 python django

我正在使用更新或创建模型,如下所示:

device_inv = Inventory.objects.update_or_create(
    defaults={
            'location' : site,
            'device' : dev_name
        },
    device = dev_name
)
Run Code Online (Sandbox Code Playgroud)

我认为我可以使用 device_inv.id 的帖子。但是 printi device_inv 我得到一个对象和 False,我认为它是对象以及它是更新还是创建的答案?(真被创建,假被编辑)

>>> print device_inv
(<Inventory: Inventory object>, False)
Run Code Online (Sandbox Code Playgroud)

我还尝试了几种尝试访问该对象的方法,但似乎都没有奏效。

>>> for i in device_inv[0]:
...  print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Inventory' object is not iterable
>>> print device_inv[0]["id"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Inventory' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?

sch*_*ggl 5

id 是对象实例的一个属性:

device_inv[0].id
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

device_inv, created = Inventory.objects.update_or_create(...)
print device_inv.id
Run Code Online (Sandbox Code Playgroud)