这是我的models.py:
class Category(models.Model):
category = models.CharField(max_length=50, verbose_name=u"文章分类", default="")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"文章分类"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.category
class Article(models.Model):
category = models.ForeignKey(Category, verbose_name=u"文章分类")
title = models.CharField(max_length=100, verbose_name=u"文章题目", default="")
content = UEditorField(width=1000, height=500,imagePath="media/", filePath="media/",verbose_name=u"文章内容")
read_nums = models.IntegerField(default=0, verbose_name=u"阅读量")
comment_nums = models.IntegerField(default=0, verbose_name=u"评论数")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"文章"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.title
现在我需要在此页面的django-admin页面显示类别中的文章数量:
我该怎么办?
答案 0 :(得分:0)
您可以通过管理类的list_display
添加自定义列。在那里,您只需添加方法that you add to your model (or the admin)并返回所需的值:
class Category(models.Model):
# ...
def article_count(self):
return self.article_set.count()
article_count.short_description = 'Number of articles' # displayed as label/column header
class CategoryAdmin(admin.ModelAdmin):
readonly_fields = ['article_count'] # this is your custom method
list_display = ['__str__', 'article_count', 'add_time']
admin.site.register(Category, CategoryAdmin)