Reputation:
I suppose that the object IDs are auto created. Although, I encounter an Attribute error saying "'list' object has no attribute 'id'"
Below is my code module:
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')
Upvotes: 1
Views: 208
Reputation: 1730
If you want to create Building
objects for each of the Client
objects then you can do this:
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)
But be aware, if you aren't already doing so, it would be preferable to link these two models with a foreign key rather than manually recording the client_id
on instances of Building
, if that is in fact what you are doing here. I'd have to see your models.py
file though to work out what you are actually up to in order to give you further advice about that.
Upvotes: 1
Reputation: 3853
names = ['WaltDisney', 'Google', 'JetAirways']
now = timezone.now()
clients = Client.objects.bulk_create(
[Client(name=name, created_at=now, updated_at=now) for name in names]
)
buildings = [
c.building_set.create(
description='TestBuilding',
is_active=1,
country_code='NL',
) for c in clients
]
Upvotes: 0