Home > Blockchain >  Django Admin, use list_filter, based on foreing key field
Django Admin, use list_filter, based on foreing key field

Time:02-03

The app have 3 classes at model.py, and it was created a calculated field.

class Category(models.Model):
    name = models.CharField(max_length=255) 

class Asset(models.Model):
    category = models.ForeignKey(Category, related_name='categories', on_delete=models.CASCADE)

class PortfolioAsset(models.Model):
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)

    @property
    def category(self):
        return self.asset.category

I tried to add in the admin.py a list_filter:

class PortfolioAssetAdmin(admin.ModelAdmin):
    list_display =('asset', 'category' )
    list_filter =(('category', RelatedFieldListFilter),)

but i get the error message:

"PortfolioAsset has no field named category"

I think that is because category in PortfolioAsset is calculated, but don`t know how to solve that. Or if there is any better and working solution. Thanks


THE SOLUTION as Zufra said, change 'category' to 'asset__category':

list_filter =(('asset__category', RelatedFieldListFilter),)

CodePudding user response:

Try asset__category. The PortfolioAsset model does not have a field named category as the error tells you. It has a foreign key to the Asset model and this model is the one with the field category.

  •  Tags:  
  • Related