django - Django ORM 对象 ID
问题描述
我想对象 ID 是自动创建的。虽然,我遇到一个属性错误说“'list'对象没有属性'id'”
下面是我的代码模块:
client = Client.objects.bulk_create([Client(name='WaltDisnep', created_at=timezone.now(),
updated_at=timezone.now()),
Client(name='Google', created_at=timezone.now(),
updated_at=timezone.now()),
Client(name='JetAirways', created_at=timezone.now(),
updated_at=timezone.now())])
building = Building.objects.create(description='TestBuilding',
is_active=1, client_id=client.id,
country_code='NL')
解决方案
如果要Building
为每个Client
对象创建对象,则可以这样做:
clients = Client.objects.bulk_create([
Client(name='WaltDisney', created_at=timezone.now(), updated_at=timezone.now()),
Client(name='Google', created_at=timezone.now(), updated_at=timezone.now()),
Client(name='JetAirways', created_at=timezone.now(), updated_at=timezone.now())
])
# Now we have a list of clients we can iterate over.
buildings = []
for client in clients:
# Let's make the description specific per client.
description = '{} Building'.format(client.name)
building = Building.objects.create(
description=description,
is_active=True, # For truthiness use booleans not the set {0, 1}.
client_id=client.id,
country_code='NL'
)
buildings.append(building)
但请注意,如果您还没有这样做,最好用外键链接这两个模型,而不是手动记录 的client_id
on 实例Building
,如果这实际上是您在这里所做的。我必须查看您的models.py
文件才能确定您实际在做什么,以便为您提供进一步的建议。
推荐阅读
- python - 在新的 pandas 列中附加来自 pdf 的迭代匹配模式
- sql-server - SQL 错误 周转时间已过期
- hibernate - gorm 配置中的“已分配”ID 不起作用
- python - AttributeError:“系列”对象没有属性“列”
- mysql - 作为一个加入 sql 查询以获得总百分比
- java - writeObject(Object obj) 写对象的整个类吗?
- ruby - RSpec 中的简单 instance_variable_set 不起作用,但为什么不呢?
- java - 使用 ArCore 将静态对象放置在屏幕的角落
- database - APEX_ITEM 选择列表 ...所有项目都在那里但不可见
- c++ - 在 C++ 中创建两个不同的二叉树时出现分段错误