Django Admin Cookbook-41如何将数据库视图添加到Django Admin后台
返回目录
41.如何将数据库视图添加到Django Admin后台?
你通过以下语句,创建了一个数据库视图:
create view entities_entity as
select id, name from entities_hero
union
select 10000+id as id, name from entities_villain
它包含所有Hero和Villain对象的名称。Villain对象的的ID被设置都加上10000,因为Hero对象的数量不会超过这个数字。
sqlite> select * from entities_entity;
1|Krishna
2|Vishnu
3|Achilles
4|Thor
5|Zeus
6|Athena
7|Apollo
10001|Ravana
10002|Fenrir
然后添加一个managed=False模型:
class AllEntity(models.Model):
name = models.CharField(max_length=100)
class Meta:
managed = False
db_table = "entities_entity"
并将其添加到Admin后台:
@admin.register(AllEntity)
class AllEntiryAdmin(admin.ModelAdmin):
list_display = ("id", "name")
效果如下。