django:检查给定模型的 modeladmin
如何检查给定模型是否存在模型管理员?
modeladmins 是通过向 admin.site 对象注册模型来创建的。如何检查站点对象以查看已注册哪些模型以及哪个 admin_class?
How does one check to see if a modeladmin exists for a given model?
modeladmins are created by registering a model with the admin.site object. how can one check the site object to see which models have been registered, and with which admin_class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的问题,这促使我做了一些挖掘。
一旦管理类被注册,它们就会被存储在
site
对象的一个属性中,这个属性被称为 - 毫不奇怪 -_registry
。这是模型类到 modeladmin 类的字典 - 请注意,键和值都是类,而不是名称。因此,如果您有这样的 admin.py:
那么一旦实际导入 - 通常是通过 urls.py 中的
admin.autodiscover()
行 -admin.site._registry 将包含类似这样的内容:
并且您将通过使用模型本身作为键来获取
MyModel
的 ModelAdmin 对象:Interesting question, which provoked me to do a little digging.
Once the admin classes have been registered, they are stored in an attribute of the
site
object called - not surprisingly -_registry
. This is a dictionary of model classes to modeladmin classes - note both the keys and values are classes, not names.So if you have an admin.py like this:
then once that has actually been imported - usually by the
admin.autodiscover()
line in urls.py -admin.site._registry
will contain something like this:and you would get the ModelAdmin object for
MyModel
by using the model itself as the key:Django 的 django.contrib.admin.sites.AdminSite 有一个检查注册模型的方法,称为 .is_registered(model) 。此方法将检查管理网站的
_registry
属性(就像 Daniel Roseman 的方法)所以,如果你有这样的文件:
你可以做一些这样的测试:
Django's
django.contrib.admin.sites.AdminSite
has a method for checking registered Model called.is_registered(model)
. This method will check on the admin site's_registry
attribute (just like Daniel Roseman's approach)So, if you have files like these:
You could make some test like this: