首页 > 解决方案 > 在管理视图中显示内联项的计数

问题描述

我想在 django 中列出的父项中显示相关项的计数。但我不断收到错误消息。

模型.py

class TblHoldings(models.Model):
    item_code = models.CharField(unique=True, max_length=5)
    product_name = models.CharField(max_length=45)
    service_provider = models.ForeignKey(TblHoldingsServiceProviders,on_delete=models.CASCADE, related_name='service_provider',db_column='service_provider')
    account_details = models.CharField(max_length=100)
    purchase_cost = models.IntegerField()
    current_value = models.IntegerField()
    power_of = models.CharField(max_length=45, blank=True, null=True)
    purchase_date = models.DateTimeField(blank=True, null=True)
    goal_term = models.CharField(max_length=40, default="M",choices=FIN_GOAL_TERM)
    created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)

    def __str__(self):
        return self.product_name + ' at ' + self.service_provider.provider_name

    class Meta:
        verbose_name = 'Holding'
        verbose_name_plural = 'Holdings'
        managed = True
        db_table = 'tbl_holdings'

class TblHoldingsSubProducts(models.Model):
    item_code = models.CharField(max_length=5, blank=True, null=True)
    holding_id = models.ForeignKey(TblHoldings, default= 1,on_delete = models.CASCADE,related_name='holding_id', db_column='holding_id' )
    product_name = models.CharField(max_length=45)
    account_details = models.CharField(max_length=100)
    purchase_cost = models.IntegerField()
    current_value = models.IntegerField()
    power_of = models.CharField(max_length=45)
    purchase_date = models.DateTimeField(blank=True, null=True)
    maturity_date = models.DateTimeField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)


    def __str__(self):
        return self.product_name

    class Meta:
        verbose_name = 'Holdings Sub Product'
        verbose_name_plural = 'Holdings Sub Products'
        managed = True
        db_table = 'tbl_holdings_sub_products'

管理员.py

class HoldingsSubProductsInline(admin.TabularInline):
    model = TblHoldingsSubProducts

@admin.register(TblHoldings)
class HoldingsAdmin(admin.ModelAdmin):
    list_display = ('item_code', 'product_name', 'service_provider', 'power_of','current_value', 'purchase_date', 'subproduct_count')
    list_filter = ('goal_term', 'power_of', 'product_name', 'service_provider')
    ordering = ('purchase_date',)
    search_fields = ('product_name',)
    inlines = [
        HoldingsSubProductsInline,
    ]
    def subproduct_count(self, obj):
        return obj.tblholdingssubproducts_set.count()

错误

/admin/app_fin/tblholdings/ 'TblHoldings' 对象的 AttributeError 没有属性 'tblholdingssubproducts_set'

标签: djangodjango-admin

解决方案


推荐阅读