خرید بک لینک

Vote count: 0

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.

asked 4 mins ago

1 Answer

Vote count: 0

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

@property
def total_weight(self):
    retu queryset_with_sum_aotation.values('sum_value').sum_value

answered 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 2 ارديبهشت 1395 ساعت: 17:33

صفحه بندی