问题
I have searched, didn't find any answer. I want to get the total of inline salesitem
in the admin template. I want the quantity * price
of the item to be shown in the admin inline table as I add quantity.
Example:
models.py
class Stock(models.Model):
price = models.DecimalField()
quantity = models.PositiveIntegerField()
class Sales(models.Model):
name = models.CharField()
#Other fields
class SalesItem(models.Model):
item = models.ForeignKey(Stock)
quantity = models.PositiveIntegerField()
admin.py
class SalesItemInline(admin.TabularInline):
model = SalesItem
class SalesAdmin(admin.ModelAdmin, ExportCsvMixin):
exclude = ['admin', 'branch']
inlines = [SalesItemInline]
It is a mini inventory system that I already deployed.
回答1:
You can display model functions and properties in inlines. For example:
class SalesItem(models.Model):
...
@property
def total(self):
return self.item.price * self.quantity
and then add it as part of readonly_fields
(because it is a computed property):
class SalesItemInline(admin.TabularInline):
...
fields = ('item', 'quantity', 'total')
readonly_fields = ('total',)
来源:https://stackoverflow.com/questions/53054987/display-total-amount-in-the-admin-interface