首页 > 解决方案 > 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')

标签: djangodjango-ormattributeerror

解决方案


如果要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_idon 实例Building,如果这实际上是您在这里所做的。我必须查看您的models.py文件才能确定您实际在做什么,以便为您提供进一步的建议。


推荐阅读