Hirzi Nurfakhrian - 11 months ago 26

Python Question

How to make a models which the field's value is automatically set from another models's field?

Example:

1st model

`class PurchasingDetail(models.Model):`

....

weight = models.DecimalField(max_digits=8, decimal_places=2, validators=[MinValueValidator(Decimal('0.1'))], help_text="kilogram")

....

2nd model

`class Warehouse(models.Model):`

....

total_weight = models.DecimalField(max_digits=8, decimal_places=2)

....

What I want is on the

`Warehouse.total_weight`

`sum`

`weight`

`PurchasingDetail`

`PurchasingDetail`

`Warehouse`

Thanks.

Answer

Make total_weight a property that calls a queryset and then return the sum, there isn't any need to save it to the database.

```
@property
def total_weight(self):
return queryset_with_sum_annotation.values('sum_value').sum_value
```