Django admin注册model究竟要怎么写才优雅
比如在Django admin 注册models时,会用到。
对于APP里自带的models,可以使用这种方式注册。
from django.contrib import admin # Register your models here. from django.apps import apps from django.contrib.admin.sites import AlreadyRegistered app_models = apps.get_app_config("crm").get_models() # 获取app:crm下所有的model,得到一个生成器 # 遍历注册model for model in app_models: try: admin.site.register(model) except AlreadyRegistered: pass
但是如果想要扩展models在Django admin页面的显示效果时,就没法用上面的方法了,但是可以使用装饰器来简化书写的代码量。
from django.contrib import admin # Register your models here. from bbs import models @admin.register(models.Article) class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'author', 'pub_date', 'last_modify', 'status', 'priority') @admin.register(models.Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('article', 'parent_comment', 'comment_type', 'comment', 'user', 'date') @admin.register(models.Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'set_as_top_menu', 'position_index') admin.site.register(models.UserProfile)
补充一个获取模块中类名的方法。
import inspect # 找出模块里所有的类名 def get_classes(arg): classes = [] clsmembers = inspect.getmembers(arg, inspect.isclass) for (name, _) in clsmembers: classes.append(name) return classes