Reputation: 13
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
is always set sum
of all weight
on PurchasingDetail
. So, if I insert a new data on PurchasingDetail
, the Warehouse
updated.
Thanks.
Upvotes: 0
Views: 59
Reputation: 43320
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
Upvotes: 1