在Django 3.1.2中,我想将OneToOneField中的数据复制到多个字段。
我想更改
class A(models.Model):
name = models.TextField()
description = models.TextField()
class B(models.Model):
a = models.OneToOneField(A, on_delete=models.CASCADE, related_name='b_a')
至
class A(models.Model):
name = models.TextField()
description = models.TextField()
class B(models.Model):
name = models.TextField()
description = models.TextField()
同时保留现有数据。
感谢您提前抽出时间!
步骤1
class A(models.Model):
name = models.TextField()
description = models.TextField()
class B(models.Model):
a = models.OneToOneField(A, on_delete=models.CASCADE, related_name='b_a')
name = models.TextField()
description = models.TextField()
步骤2
makemigrations
migrate
def sync():
for i in B.objects.all():
i.name = i.a.name
i.description = i.a.description
i.save()
步骤3
change model B
class B(models.Model):
name = models.TextField()
description = models.TextField()
步骤4
makemigrations
migrate