how to display an attribute of a foreign key in dj

2019-02-26 09:13发布

I want to display the level of the category that the product belongs to, in the admin page for the object. snipped a lot fo the unimportant fields out of the display below.

class Category(models.Model):
    name = models.CharField(max_length=50, default=False)
    level = models.IntegerField(help_text="1, 2 ,3 or 4")

class Product(models.Model):
    category = models.ForeignKey(Category)
    name = models.CharField(max_length=100)


    prepopulated_fields = {'slug': ('name',)}
    fieldsets = [
        ('Product Info',{'fields': ['name', 'slug','partno','description']}),
        ('Categorisation',{'fields': ['brand','category']}),

obviously i've tried a little to get this working and googled a lot, but i've found reference to list_filter lots, but nothing about just showing the field. best guess was

'category__level'

anyone know the right way to do this?

3条回答
我只想做你的唯一
2楼-- · 2019-02-26 09:43

In your admin.py file

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

admin.site.register(Product, ProductAdmin)

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-26 09:53

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.

查看更多
时光不老,我们不散
4楼-- · 2019-02-26 09:58

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
查看更多
登录 后发表回答