我正在尝试将所有购买的总和显示在我的管理员中,以便我可以根据花费的金额查看收据。这是我的应用程序。我删除了我已经尝试过的内容,并粘贴了已经有效的内容。
class Store(models.Model):
store_name = models.CharField(max_length = 255)
store_number = models.IntegerField()
address_1 = models.CharField(_("address"), max_length = 128)
address_2 = models.CharField(_("address cont'd"), max_length = 128, blank = True)
city = models.CharField(_("city"), max_length = 64, default = "Enter City")
state = USStateField(_("state"), default = "AB")
zip_code = models.CharField(_("zip code"), max_length = 5, default = "Enter Zip")
def __unicode__(self):
return self.store_name
class Receipt(models.Model):
store = models.ForeignKey(Store)
receipt_number = models.IntegerField()
transaction_date = models.DateTimeField()
BUSINESS = "BS"
PERSONAL = "PS"
RECEIPT_TYPE_CHOICES = (
(PERSONAL, 'Personal'),
(BUSINESS, 'Business'),
)
receipt_type = models.CharField(max_length=2,
choices = RECEIPT_TYPE_CHOICES,
default = PERSONAL)
def __unicode__(self):
return unicode(self.receipt_number)
class Purchase(models.Model):
receipt = models.ForeignKey(Receipt)
item_name = models.CharField(max_length = 255)
price = models.DecimalField('Amount', max_digits = 5, decimal_places = 2 )
def __unicode__(self):
return self.item_name
这是我的管理员
from django.contrib import admin
from django.db.models import Sum
from receipts.models import *
class PurchaseInline(admin.TabularInline):
model = Purchase
extra = 3
class ReceiptAdmin(admin.ModelAdmin):
fieldsets = [
('Store', {'fields': ['store']}),
('Receipt', {'fields':['receipt_number', 'receipt_type']}),
('Transaction Date', {'fields': ['transaction_date']}),
]
inlines = [PurchaseInline]
list_display = ('store', 'transaction_date', 'receipt_number', 'receipt_type')
list_filter = ['store']
class StoreAdmin(admin.ModelAdmin):
list_display = ('store_name', 'city', 'state', 'store_number')
admin.site.register(Store, StoreAdmin)
admin.site.register(Receipt, ReceiptAdmin)
对于收据中添加的每笔购买金额,我希望能够在管理/收据索引中显示购买总金额。
所以
Receipt 1
purchase 1 = 100.00
purchase 2 = 200.00
保存该收据并返回收据索引后,我希望能够查看每张收据的总金额。因此收据1将显示“收据编号”“商店”....总计(300.00)
答案 0 :(得分:0)
在ReceiptAdmin
中定义一个函数,如下所示,并在管理字段列表中添加函数名称:
class ReceiptAdmin(admin.ModelAdmin):
....
('Receipt', {'fields':['receipt_number', 'receipt_type', 'receipt_amount']}),
....
def receipt_amount(self, request):
current_receipt_purchase_amounts = Purchase.objects.filter(receipt__id = request.id).values_list('price', flat = True)
total_amount = sum(current_receipt_purchase_amounts)
return total_amount
receipt_amount.short_description = 'Receipt Amount'
这样可行。