Display Total amount in the admin interface

僤鯓⒐⒋嵵緔 提交于 2020-01-23 12:00:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!