Not sure if this is possible, but in my Cart (model class) detail view in Django Admin, I'd like to total up all of my TabularInline Entry model class subtotals, and save that value to my Cart's total_price attribute. Is there a way to do this or somehow use a filter or form widget to add all the subtotals together for the same purpose? Thanks in advance for any help!
Below is an example of what I'd like to do. You can see in the total price field I manually entered 130 (subtotal's: 90 + 20 + 20 = 130). I'd like this to be calculated automatically each time an entry is added from inventory, and its quantity edited.
So far in my admin.py I have a TabularInline admin class that returns the subtotal for each entry by multiplying its quantity by its respective price. Then my CartAdmin class displays that inline relationship inside the cart model detail view.
admin.py
class EntryInline(admin.TabularInline):
model = Entry
extra = 0
readonly_fields = ['subtotal']
exclude = ['price']
def subtotal(self, obj):
return "$" + str(obj.quantity * obj.inventory.price)
class CartAdmin(admin.ModelAdmin):
inlines = [EntryInline]
fieldsets = (
(None, {
'fields':('user', 'total_price')
}),
)
models.py
class Inventory(models.Model):
quantity = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2)
class Cart(models.Model):
user = models.OneToOneField(User)
total_price = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
class Entry(models.Model):
cart = models.ForeignKey(Cart, related_name="entries")
inventory = models.ForeignKey(Inventory, related_name="entries")
quantity = models.PositiveSmallIntegerField(default=1)
price = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
You can try fetching the total_price in cart admin and populating the field as:
Regarding your Import error , import F and Sum as:
Or if you want more dynamic control, so that whenever a user edits the quantity in the entry inline, the total_price should update automatically you can write custom javascript for it.
Hope it helps.