django-Runpython函数将charfield转换为Foreignkey

时间:2018-12-21 14:04:16

标签: python django

我一直努力将loginForm frm = new loginForm(); frm.ShowDialog(); 导入的数据模型与基于csv的空间数据模型相关联。

我已经创建了两个模型,现在我试图将数据从一个字段传输到新的CharField字段。我做了一个ForeignKey函数以应用于迁移,但是它消除了一个错误:

Runpython

以下是模型:

ValueError: Cannot assign "'921-5'":
  "D2015ccccccc.rol_fk" must be a "D_Base_Roles" instance.

class D_Base_Roles(models.Model): predio = models.CharField(max_length=254) dest = models.CharField(max_length=254) dir = models.CharField(max_length=254) rol = models.CharField(primary_key=True, max_length=254) vlr_tot = models.FloatField() ub_x2 = models.FloatField() ub_y2 = models.FloatField() instrum = models.CharField(max_length=254) codzona = models.CharField(max_length=254) nomzona = models.CharField(max_length=254) geom = models.MultiPointField(srid=32719) def __str__(self): return str(self.rol) class Meta(): verbose_name_plural = "Roles" class D2015ccccccc(models.Model): id = models.CharField(primary_key=True, max_length=80) nombre_archivo = models.CharField(max_length=180, blank=True, null=True) derechos = models.CharField(max_length=120, blank=True, null=True) dir_calle = models.CharField(max_length=120, blank=True, null=True) dir_numero = models.CharField(max_length=120, blank=True, null=True) fecha_certificado = models.CharField(max_length=50, blank=True, null=True) numero_certificado = models.CharField(max_length=50, blank=True, null=True) numero_solicitud = models.CharField(max_length=50, blank=True, null=True) rol_sii = models.CharField(max_length=50, blank=True, null=True) zona_prc = models.CharField(max_length=120, blank=True, null=True) ##NEW EMPTY FOREIGNKEY FIELD rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.numero_certificado) class Meta: managed = True #db_table = 'domperm2015cip' verbose_name_plural = "2015 Certificados Informaciones Previas" ordering = ['numero_certificado'] 函数:

Runpython

def pop_rol(apps, schema_editor): roles = apps.get_model('b_dom_edificacion', 'D2015ccccccc') for r in roles.objects.all(): rol = roles r.rol_fk = r.rol_sii r.save() 的值都是唯一的,而D_Base_Roles.rol是这些值之一。

我想念什么?

1 个答案:

答案 0 :(得分:0)

您可能需要分配一个对象,而不是字符串。更改行

r.rol_fk = r.rol_sii

r.rol_fk = D_Base_Roles.objects.get(rol=r.rol_sii)

也许可以调整为查找D_Base_Roles实例的正确字段。

注意:这将对for循环的每次迭代进行数据库查询