一个model注册多个ModelAdmin
关键字: Meta , proxy = True, def get_queryset
默认情况下是不允许一个model注册多个ModelAdmin的,需要做扩展配置:
这里从News扩展出来两个Model (ImageNews,PaperNews)
class News(models.Model):
category_choices = [
(1, "42区"),
(2, "段子"),
(3, "图片"),
(4, "挨踢1024"),
(5, "你问我答")
]
title = models.CharField(max_length=100, default="")
summary = models.TextField(default="", max_length=500)
href = models.URLField(max_length=100, default="")
category = models.IntegerField(choices=category_choices)
image = models.ImageField(upload_to="article_image/%Y/%m", default="article_image/default.png", max_length=100)
add_time = models.DateTimeField(auto_now_add=True)
recommend = models.IntegerField(default=0)
publisher = models.ForeignKey(UserInfo)
class Meta:
verbose_name = "新闻"
verbose_name_plural = verbose_name
def __str__(self):
return self.title
def get_comment_nums(self):
return self.usercomment_set.all().count()
class ImageNews(News):
class Meta:
verbose_name = "图片新闻"
verbose_name_plural = verbose_name
proxy = True
class PaperNews(News):
class Meta:
verbose_name = "文章新闻"
verbose_name_plural = verbose_name
proxy = True
编写三个ModelAdmin
class NewsAdmin(admin.ModelAdmin):
list_display = ["title", "summary", "publisher", "href", "category", "recommend", "add_time"]
raw_id_fields = ["publisher"]
class ImageNewsAdmin(admin.ModelAdmin):
list_display = ["title", "summary", "publisher", "href", "category", "recommend", "add_time"]
raw_id_fields = ["publisher"]
def get_queryset(self, request):
qs = super(ImageNewsAdmin, self).get_queryset(request)
qs = qs.filter(category=3)
return qs
class PaperNewsAdmin(admin.ModelAdmin):
list_display = ["title", "summary", "publisher", "href", "category", "recommend", "add_time"]
raw_id_fields = ["publisher"]
def get_queryset(self, request):
qs = super(PaperNewsAdmin, self).get_queryset(request)
qs = qs.filter(category=2)
return qs
admin.site.register(News, NewsAdmin)
admin.site.register(ImageNews, ImageNewsAdmin)
admin.site.register(PaperNews, PaperNewsAdmin)