我试图更新当前模型中的布尔字段,当第二个模型中的两个量与FK相等时。
这是一对多关系,所以我需要检查外键的每个实例的两个数量是否相等。
我认为我想做的事情会奏效,但我不确定如何写它。我现在只在Python / Django工作了几个星期
class ModelA():
model_number = models.CharField(max_length=100)
is_true = models.BooleanField(default=False)
def update_is_true(self, *args, **kwargs):
disting_model = ModelB.objects.filter(
model_number=self.model_number
)
pod = self.modelb_set.all()
ordered = sum([p.ordered for p in pod])
received = sum([p.qty_received for p in pod])
if received >= ordered:
self.is_true = True
self.save()
"""
get a count for every instance of (ordered != received)
for each model_number. If count = 0, set (is_true = True)
"""
class ModelB():
model_number = models.ForeignKey(ModelA), on_delete=models.PROTECT)
ordered = models.IntegerField(default=0)
received = models.IntegerField(default=0)
这是我的数据库结构。
ModelA
id model_number is_true
1 1 False
ModelB
id modelA_id ordered received
1 1 15 15
2 1 25 25