Reputation: 159
I am trying to pass a dict to bulk_create, but it is not working. If someone has used this prior, I would appreciate advice.
Django Server Model:
class Servers(models.Model):
name = models.CharField(('name'), max_length=128)
location = models.OneToOneField('locations.Location', on_delete=models.CASCADE)
ip_address = models.CharField(('ip_address'), max_length=128)
date = models.DateField(auto_now=True)
Django Location Model:
class Location(models.Model):
city = models.CharField(('city'), max_length=10)
geolocation = models.PointField(('location'))
A print of my dict:
{
'Florida': {
'name' : 'server-a',
'location':'Miami',
'ip_address':'172.16.16.1',
},
'Colorado': {
'name' : 'server-b',
'location':'Denver',
'ip_address':'172.16.24.1',
},
My function:
def add_to_db(data_dict):
Servers.objects.bulk_create(Servers(**d) for d in data_dict.values())
My error:
ValueError: Cannot assign "'Florida'": "Server.location" must be a "Location" instance.
Upvotes: 1
Views: 1349
Reputation: 47354
Since location
is OneToOne field you need to pass as location
argument location object. Or you can pass location_id
instead.
Change data to this:
{
'Florida': {
'name' : 'server-a',
'location_id':1,
'ip_address':'172.16.16.1',
},
'Colorado': {
'name' : 'server-b',
'location_id':2,
'ip_address':'172.16.24.1',
},
Upvotes: 3