将动态生成的列添加到Django管理列表视图

时间:2019-01-30 14:31:36

标签: django django-models django-views

Backgorund

我有以下两种模型:

TYPE_CHOICES = (
    (0, 'Income'),
    (1, 'Outcome'),
)

class Transaction(models.Model):
    type = models.IntegerField(choices=TYPE_CHOICES)
    amount = models.IntegerField()
    store = ForeignKey(Store)

class Store(models.Model):
    name = models.CharField(max_length=300)
    email = models.EmailField(max_length=300)
    balance = models.ForeignKey(Transaction)

我需要实现的目标

当前,django在模型移动的“管理员”列表视图中显示此输出(假设我们有两个商店):

Type     Amount  Store
------------------------
Income   100     Store A
Outcome  20      Store A
Income   500     Store B

我想显示自定义列,每列显示商店的部分余额:

Type     Amount  Store    Store A Balance  Store B Balance
----------------------------------------------------------
Income   100     Store A  100              0
Outcome  20      Store A  80               0
Income   500     Store B  80               500

我知道如何创建自定义静态列,并且知道如何计算行的值,但是我无法弄清楚如何使列动态化,即根据其他模型进行显示。

PS :请注意,商店的编号可能会更改。如果我添加新商店,则该商店的部分余额也应显示在列表视图中。

1 个答案:

答案 0 :(得分:0)

向管理员添加模型时,您可以将管理类中的方法显示为列表的列:

class AdminTransaction(admin.ModelAdmin):
    list_display = ('type', 'amount', 'store', 'dynamic')

    def dynamic(self, obj):
       # obj here is the object in this row of the list.
       # Lets say you want to show the difference between the amount of
       # the current transaction and the maximum amount is known then:
       maximum_known = AdminTransaction.objects.aggregate(max_amount=MAX('amount'))
       return maximum_known['max_amount'] - obj.amount

参考:https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display