How to display an attribute of a foreign key in the Django admin page

前端 未结 3 402
独厮守ぢ
独厮守ぢ 2021-01-18 17:34

I want to display the level field of the category to which the product is related on the object\'s admin page.

    class Category(m         


        
相关标签:
3条回答
  • 2021-01-18 17:48

    In your admin.py file

    class ProductAdmin(admin.ModelAdmin):
        list_display = ('name', 'category__level', 'category')
    
    admin.site.register(Product, ProductAdmin)
    

    Try this.............

    0 讨论(0)
  • 2021-01-18 17:52

    The simplest way is to put the level of the Category into the __unicode__ method:

    class Category(models.Model):
        name = models.CharField(max_length=50, default=False)
        level = models.IntegerField(help_text="1, 2 ,3 or 4")
    
        def __unicode__(self):
            return u'%s [%d]' % (self.name, self.level)
    

    So the select box will show it.

    0 讨论(0)
  • 2021-01-18 17:57

    Define a method on the ModelAdmin class which returns the value of the related field, and include that in list_display.

    class ProductAdmin(admin.ModelAdmin):
        list_display = ('name', 'level')
        model = Product
    
        def level(self, obj):
            return obj.category.level
    
    0 讨论(0)
提交回复
热议问题