有没有任何官方的方式来获得一个模型的管理选项?

2024-04-26 02:52:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要获取在模型的管理选项上定义的search_fields属性。很久以前,它非常简单和直接(但没有文档记录),即model._meta.admin.search_fields。在

找到管理员是最困难的部分,我能找到的最接近的是:

def admin_options(model):
    from django.contrib import admin
    return admin.site._registry.get(model)

我找不到记录的._registry成员(下划线似乎暗示它不是公共的)。这也不适用于尚未运行admin.autodiscover()的站点。备用代码执行以下操作:

^{pr2}$

有没有一种官方(或更简单)的方式来获取模型的管理选项?在


Tags: 文档模型fieldssearchmodel属性定义admin
2条回答

您需要确保注册代码已运行,否则站点将不包含注册表中的(model,modeladmin)。在

在代码.py在

from django.contrib.admin.sites import site

# run admin registration code before we get here
for model, model_admin in site._registry.items():
    if model == whatevermodel: 
        print(model_admin.search_fields)

先创建模型

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
class LocationCode(models.Model):
    """
    A web service that will allow user to create there price rule based on conditions
    """
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

在管理员py你需要添加代码

^{pr2}$

在网址.py添加这些行

from django.contrib import admin
admin.autodiscover()

相关问题 更多 >