Get foreign key, and corresponding field values into model

时间:2017-06-12 17:06:03

标签: django

I have a model which I am using a foreign key from another model. I need to also set another column to a corresponding field of that foreign key but am unsure how to do so correctly.

I am wanting to do it this way to work with a function I have setup in ModelC that should match the po_number from ModelA, then match the sku_number on Model B in the save() function.

Class ModelA(models.Model):
    po_number = models.CharField(max_length=100)


Class ModelB(models.Model):
    model_a = models.ForeignKey(ModelA, on_delete=models.PROTECT
    Value = models.CharField(max_length=100)
    sku_number = models.CharField(max_length=100)

    def calc_received(self):
        sum_value = ModelC.objects.filter(
            sku_number=self.sku_number
          ).aggregate(
              value_sum=Sum(F('value'))
          )
          value_received = sum_value['value_sum']

          return value_received


Class ModelC(models.Model):
    po_number = models.CharField(max_length=100)
    sku_number = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        obj = ModelB.objects.get(
            po_number=self.po_number,
            sku_number = self.sku_number
          )

        obj.value_received = obj.calc_received()
        obj.save()

How can I get the db structure to be something similiar to:

id     ModelA_id     ValueFromA
_______________________________

Currently I am trying

def _get_valuefromB(self):
    return self.ModelB.Value
value = property(_get_valuefromB

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你需要这样的东西

class ModelA(models.Model):
    model_b = models.ForeignKey(ModelB, on_delete=models.PROTECT)

    @property
    def value_b(self):
        return self.model_b.Value