Django bulk_create不起作用

时间:2018-02-26 09:37:07

标签: django django-models

我正在尝试将dict传递给bulk_create,但它无效。如果有人使用过这个,我会很感激建议。

Django服务器模型:

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位置模型:

class Location(models.Model):
    city = models.CharField(('city'), max_length=10)
    geolocation = models.PointField(('location'))

我的字典:

{
    'Florida': {
        'name' : 'server-a',
        'location':'Miami',
        'ip_address':'172.16.16.1',
    },
    'Colorado': {
        'name' : 'server-b',
        'location':'Denver',
        'ip_address':'172.16.24.1',
},

我的功能:

def add_to_db(data_dict):
    Servers.objects.bulk_create(Servers(**d) for d in data_dict.values())

我的错误:

ValueError: Cannot assign "'Florida'": "Server.location" must be a "Location" instance.

1 个答案:

答案 0 :(得分:2)

由于location是OneToOne字段,因此您需要传递location参数位置对象。或者您也可以通过location_id。 将数据更改为:

{
    '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',
},