为什么在Django上使用bulk_create通过外键插入数据会返回“属性对象不可调用”?

时间:2019-03-25 12:36:52

标签: python django sqlite

我正在将Django 2.17与SQLite 3.26数据库配合使用,并尝试从csv文件插入数据。我正在使用get_or_create方法,但是速度太慢。因此,我开始尝试使用bulk_create进行插入。

我正在使用以下“模型”字段:

class SENSOR_TEMPERATURA(models.Model):
    ID_Sensor_Temperatura = models.AutoField(primary_key = True)

class VALOR_TEMPERATURA(models.Model):
    ID_Valor_Temperatura = models.AutoField(primary_key = True)
    ID_Sensor_Temperatura = models.ForeignKey(SENSOR_TEMPERATURA, on_delete = models.PROTECT, null = False, db_column = 'VATE_CD_ID_Sensor_Temperatura')
    Data_De_Medição = models.DateTimeField(default = datetime.now(), null = False)
    Valor = models.DecimalField(default = 0, null = False, max_digits = 30, decimal_places = 15)

我要运行的代码是:

     print (datetime.datetime.now())         
     reader = csv.reader(f) 
     insert_CSV = [] 
     count = 1 
     for row in reader: 
         insert_CSV.append([ 
         VALOR_TEMPERATURA.pk(ID_Valor_Temperatura = count), 
         VALOR_TEMPERATURA(Data_De_Medição = datetime.datetime.strptime(row[0] + " UTC-0300",'%d/%m/%Y %H:%M:%S %Z%z')), 
         VALOR_TEMPERATURA(Valor = float(row[1])), 
         VALOR_TEMPERATURA(ID_Sensor_Temperatura = SENSOR_TEMPERATURA.objects.get(ID_Sensor_Temperatura = 4)) 
         ]) 
         count = count + 1 
     print (datetime.datetime.now()) 
     VALOR_TEMPERATURA.objects.bulk_create(insert_CSV) 
     print (datetime.datetime.now()) 

我认为给我带来麻烦的部分是“ ID_Sensor_Temperatura = SENSOR_TEMPERATURA.objects.get(ID_Sensor_Temperatura = 4))”,但这正是我使用get_or_create时定义外键的方式,因此我无法弄清楚找出问题所在。

我遇到以下错误:

  6     for row in reader:
  7         insert_CSV.append([
  8         VALOR_TEMPERATURA.pk(VATE_CD_ID_Valor_Temperatura = count),
  9         VALOR_TEMPERATURA(VATE_DF_Data_De_Medição = datetime.datetime.strptime(row[0] + " UTC-0300",'%d/%m/%Y %H:%M:%S %Z%z')),
 10         VALOR_TEMPERATURA(VATE_VL_Valor = float(row[1])),

TypeError: 'property' object is not callable

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

这不是您编写Python的方式。您需要创建该对象的实例,并将其值传递给它。

insert_CSV.append( 
     VALOR_TEMPERATURA(
        ID_Valor_Temperatura=count, 
         Data_De_Medição=datetime.datetime.strptime(row[0] + " UTC-0300",'%d/%m/%Y %H:%M:%S %Z%z')), 
         Valor=float(row[1]), 
         ID_Sensor_Temperatura=SENSOR_TEMPERATURA.objects.get(ID_Sensor_Temperatura=4)
     )
)

还请注意,您的模型不应该在ALL_CAPS中定义,因为它们不是常量。他们应该被称为ValorTemperatura和SensorTemperatura。