当更新另一个模态字段时更新模型字段
Update a model field when another modal field is updated
有两个模型:
class A(models.Model):
project_code = models.CharField(max_length=250, null=False, blank=False)
reference_code = models.CharField(max_length=250, null=False, blank=False, unique=True)
quantity = models.CharField(
max_length=250,
null=True,
blank=True,
)
class B(models.Model):
project_id = models.IntegerField(
null=False,
blank=False,
default=0,
)
quantity = models.CharField(
max_length=250,
null=True,
blank=True,
)
我想在 A.quantity
发生变化时更新 B.quantity
。我怎样才能同步这两个字段?
创建 B
对象时,B.quantity
总是从现有的 A.quantity
中获取值。
我一直在研究和 found this 在官方文档中,但我不清楚如何 'synchronize' Many-to-one relationships
使用单个字段,因为它似乎同步整个table.
您可以覆盖A模型的保存方法。也可以使用django signals实现,但是重写save方法更方便清晰。
def save(self, *args, **kwargs):
super().save(args, kwargs)
B.objects.filter(<relation_field>).update(quantity=self.quantity)
有两个模型:
class A(models.Model):
project_code = models.CharField(max_length=250, null=False, blank=False)
reference_code = models.CharField(max_length=250, null=False, blank=False, unique=True)
quantity = models.CharField(
max_length=250,
null=True,
blank=True,
)
class B(models.Model):
project_id = models.IntegerField(
null=False,
blank=False,
default=0,
)
quantity = models.CharField(
max_length=250,
null=True,
blank=True,
)
我想在 A.quantity
发生变化时更新 B.quantity
。我怎样才能同步这两个字段?
创建 B
对象时,B.quantity
总是从现有的 A.quantity
中获取值。
我一直在研究和 found this 在官方文档中,但我不清楚如何 'synchronize' Many-to-one relationships
使用单个字段,因为它似乎同步整个table.
您可以覆盖A模型的保存方法。也可以使用django signals实现,但是重写save方法更方便清晰。
def save(self, *args, **kwargs):
super().save(args, kwargs)
B.objects.filter(<relation_field>).update(quantity=self.quantity)